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;
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 ($field == 'id') {
726 $row[$field] = $iterationDAO->contact_id
;
727 // special case for calculated field
729 elseif ($field == 'source_contact_id') {
730 $row[$field] = $iterationDAO->contact_id
;
732 elseif ($field == 'pledge_balance_amount') {
733 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
734 // special case for calculated field
736 elseif ($field == 'pledge_next_pay_amount') {
737 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
739 elseif (array_key_exists($field, self
::$relationshipTypes)) {
740 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
741 $relationQuery[$field]->convertToPseudoNames($relDAO);
742 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
744 elseif (isset($fieldValue) &&
747 //check for custom data
748 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
749 $row[$field] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
752 elseif (in_array($field, array(
757 //special case for greeting replacement
758 $fldValue = "{$field}_display";
759 $row[$field] = $iterationDAO->$fldValue;
762 //normal fields with a touch of CRM-3157
766 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
769 case 'state_province':
770 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
774 case 'preferred_communication_method':
775 case 'preferred_mail_format':
776 case 'communication_style':
777 $row[$field] = $i18n->crm_translate($fieldValue);
781 if (isset($metadata[$field])) {
782 // No I don't know why we do it this way & whether we could
783 // make better use of pseudoConstants.
784 if (!empty($metadata[$field]['context'])) {
785 $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
788 if (!empty($metadata[$field]['pseudoconstant'])) {
789 // This is not our normal syntax for pseudoconstants but I am a bit loath to
790 // call an external function until sure it is not increasing php processing given this
791 // may be iterated 100,000 times & we already have the $imProvider var loaded.
792 // That can be next refactor...
793 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
794 // but I have to reach a stable point....
795 $varName = $metadata[$field]['pseudoconstant']['var'];
797 $row[$field] = $labels[$fieldValue];
802 $row[$field] = $fieldValue;
807 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
808 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
809 $payFieldMapper = array(
810 'componentPaymentField_total_amount' => 'total_amount',
811 'componentPaymentField_contribution_status' => 'contribution_status',
812 'componentPaymentField_payment_instrument' => 'pay_instru',
813 'componentPaymentField_transaction_id' => 'trxn_id',
814 'componentPaymentField_received_date' => 'receive_date',
816 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
819 // if field is empty or null
824 // add payment headers if required
825 if ($addPaymentHeader && $paymentFields) {
826 // @todo rather than do this for every single row do it before the loop starts.
827 // where other header definitions take place.
828 $headerRows = array_merge($headerRows, $paymentHeaders);
829 foreach (array_keys($paymentHeaders) as $paymentHdr) {
830 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
835 $exportTempTable = self
::createTempTable($sqlColumns);
838 //build header only once
841 // If specific payment fields have been selected for export, payment
842 // data will already be in $row. Otherwise, add payment related
843 // information, if appropriate.
844 if ($addPaymentHeader) {
845 if (!$selectedPaymentFields) {
846 if ($paymentFields) {
847 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
848 if (!is_array($paymentData) ||
empty($paymentData)) {
849 $paymentData = $nullContributionDetails;
851 $row = array_merge($row, $paymentData);
853 elseif (!empty($paymentDetails)) {
854 $row = array_merge($row, $nullContributionDetails);
858 //remove organization name for individuals if it is set for current employer
859 if (!empty($row['contact_type']) &&
860 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
862 $row['organization_name'] = '';
865 // add component info
866 // write the row to a file
867 $componentDetails[] = $row;
869 // output every $tempRowCount rows
870 if ($count %
$tempRowCount == 0) {
871 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
872 $componentDetails = array();
875 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
876 $limitReached = TRUE;
878 $offset +
= $rowCount;
881 if ($exportTempTable) {
882 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
884 // if postalMailing option is checked, exclude contacts who are deceased, have
885 // "Do not mail" privacy setting, or have no street address
886 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
887 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
889 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
892 // do merge same address and merge same household processing
893 if ($mergeSameAddress) {
894 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
897 // merge the records if they have corresponding households
898 if ($mergeSameHousehold) {
899 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$memberOfHouseholdRelationshipKey);
900 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$headOfHouseholdRelationshipKey);
904 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
906 // In order to be able to write a unit test against this function we need to suppress
907 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
908 if (empty($exportParams['suppress_csv_for_testing'])) {
909 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
912 // return tableName and sqlColumns in test context
913 return array($exportTempTable, $sqlColumns);
916 // delete the export temp table and component table
917 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
918 CRM_Core_DAO
::executeQuery($sql);
919 CRM_Core_DAO
::reenableFullGroupByMode();
920 CRM_Utils_System
::civiExit();
923 CRM_Core_DAO
::reenableFullGroupByMode();
924 throw new CRM_Core_Exception(ts('No records to export'));
929 * Name of the export file based on mode.
931 * @param string $output
939 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
941 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
942 return ts('CiviCRM Contact Search');
944 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
945 return ts('CiviCRM Contribution Search');
947 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
948 return ts('CiviCRM Member Search');
950 case CRM_Export_Form_Select
::EVENT_EXPORT
:
951 return ts('CiviCRM Participant Search');
953 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
954 return ts('CiviCRM Pledge Search');
956 case CRM_Export_Form_Select
::CASE_EXPORT
:
957 return ts('CiviCRM Case Search');
959 case CRM_Export_Form_Select
::GRANT_EXPORT
:
960 return ts('CiviCRM Grant Search');
962 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
963 return ts('CiviCRM Activity Search');
968 * Handle import error file creation.
970 public static function invoke() {
971 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
972 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
973 if (empty($parserName) ||
empty($type)) {
977 // clean and ensure parserName is a valid string
978 $parserName = CRM_Utils_String
::munge($parserName);
979 $parserClass = explode('_', $parserName);
981 // make sure parserClass is in the CRM namespace and
982 // at least 3 levels deep
983 if ($parserClass[0] == 'CRM' &&
984 count($parserClass) >= 3
986 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
987 // ensure the functions exists
988 if (method_exists($parserName, 'errorFileName') &&
989 method_exists($parserName, 'saveFileName')
991 $errorFileName = $parserName::errorFileName($type);
992 $saveFileName = $parserName::saveFileName($type);
993 if (!empty($errorFileName) && !empty($saveFileName)) {
994 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
995 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
996 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
997 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
998 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1000 readfile($errorFileName);
1004 CRM_Utils_System
::civiExit();
1008 * @param $customSearchClass
1009 * @param $formValues
1012 public static function exportCustom($customSearchClass, $formValues, $order) {
1013 $ext = CRM_Extension_System
::singleton()->getMapper();
1014 if (!$ext->isExtensionClass($customSearchClass)) {
1015 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1018 require_once $ext->classToPath($customSearchClass);
1020 $search = new $customSearchClass($formValues);
1022 $includeContactIDs = FALSE;
1023 if ($formValues['radio_ts'] == 'ts_sel') {
1024 $includeContactIDs = TRUE;
1027 $sql = $search->all(0, 0, $order, $includeContactIDs);
1029 $columns = $search->columns();
1031 $header = array_keys($columns);
1032 $fields = array_values($columns);
1035 $dao = CRM_Core_DAO
::executeQuery($sql);
1037 if (method_exists($search, 'alterRow')) {
1040 while ($dao->fetch()) {
1043 foreach ($fields as $field) {
1044 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
1045 $row[$field] = $dao->$unqualified_field;
1048 $search->alterRow($row);
1053 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1054 CRM_Utils_System
::civiExit();
1058 * @param \CRM_Export_BAO_ExportProcessor $processor
1059 * @param $sqlColumns
1062 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
1063 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1066 $queryFields = $processor->getQueryFields();
1068 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1069 if ($fieldName == 'id') {
1070 $fieldName = 'civicrm_primary_id';
1073 // early exit for master_id, CRM-12100
1074 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1075 // also for current_employer, CRM-16939
1076 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1077 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1081 if (substr($fieldName, -11) == 'campaign_id') {
1083 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1087 $lookUp = array('prefix_id', 'suffix_id');
1088 // set the sql columns
1089 if (isset($queryFields[$field]['type'])) {
1090 switch ($queryFields[$field]['type']) {
1091 case CRM_Utils_Type
::T_INT
:
1092 case CRM_Utils_Type
::T_BOOLEAN
:
1093 if (in_array($field, $lookUp)) {
1094 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1097 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1101 case CRM_Utils_Type
::T_STRING
:
1102 if (isset($queryFields[$field]['maxlength'])) {
1103 $sqlColumns[$fieldName] = "$fieldName varchar({$queryFields[$field]['maxlength']})";
1106 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1110 case CRM_Utils_Type
::T_TEXT
:
1111 case CRM_Utils_Type
::T_LONGTEXT
:
1112 case CRM_Utils_Type
::T_BLOB
:
1113 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1114 $sqlColumns[$fieldName] = "$fieldName longtext";
1117 case CRM_Utils_Type
::T_FLOAT
:
1118 case CRM_Utils_Type
::T_ENUM
:
1119 case CRM_Utils_Type
::T_DATE
:
1120 case CRM_Utils_Type
::T_TIME
:
1121 case CRM_Utils_Type
::T_TIMESTAMP
:
1122 case CRM_Utils_Type
::T_MONEY
:
1123 case CRM_Utils_Type
::T_EMAIL
:
1124 case CRM_Utils_Type
::T_URL
:
1125 case CRM_Utils_Type
::T_CCNUM
:
1127 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1132 if (substr($fieldName, -3, 3) == '_id') {
1133 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1135 elseif (substr($fieldName, -5, 5) == '_note') {
1136 $sqlColumns[$fieldName] = "$fieldName text";
1139 $changeFields = array(
1145 if (in_array($fieldName, $changeFields)) {
1146 $sqlColumns[$fieldName] = "$fieldName text";
1149 // set the sql columns for custom data
1150 if (isset($queryFields[$field]['data_type'])) {
1152 switch ($queryFields[$field]['data_type']) {
1154 // May be option labels, which could be up to 512 characters
1155 $length = max(512, CRM_Utils_Array
::value('text_length', $queryFields[$field]));
1156 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1160 case 'StateProvince':
1162 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1166 $sqlColumns[$fieldName] = "$fieldName text";
1170 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1175 $sqlColumns[$fieldName] = "$fieldName text";
1183 * @param string $tableName
1185 * @param $sqlColumns
1187 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1188 if (empty($details)) {
1197 $id = CRM_Core_DAO
::singleValueQuery($sql);
1202 $sqlClause = array();
1204 foreach ($details as $dontCare => $row) {
1206 $valueString = array($id);
1207 foreach ($row as $dontCare => $value) {
1208 if (empty($value)) {
1209 $valueString[] = "''";
1212 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1215 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1218 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1220 $sqlValueString = implode(",\n", $sqlClause);
1223 INSERT INTO $tableName $sqlColumnString
1224 VALUES $sqlValueString
1226 CRM_Core_DAO
::executeQuery($sql);
1230 * @param $sqlColumns
1234 public static function createTempTable(&$sqlColumns) {
1235 //creating a temporary table for the search result that need be exported
1236 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
1238 // also create the sql table
1239 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1240 CRM_Core_DAO
::executeQuery($sql);
1243 CREATE TABLE {$exportTempTable} (
1244 id int unsigned NOT NULL AUTO_INCREMENT,
1246 $sql .= implode(",\n", array_values($sqlColumns));
1251 // add indexes for street_address and household_name if present
1252 $addIndices = array(
1255 'civicrm_primary_id',
1258 foreach ($addIndices as $index) {
1259 if (isset($sqlColumns[$index])) {
1261 INDEX index_{$index}( $index )
1267 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1270 CRM_Core_DAO
::executeQuery($sql);
1271 return $exportTempTable;
1275 * @param string $tableName
1276 * @param $headerRows
1277 * @param $sqlColumns
1278 * @param array $exportParams
1280 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1281 // check if any records are present based on if they have used shared address feature,
1282 // and not based on if city / state .. matches.
1284 SELECT r1.id as copy_id,
1285 r1.civicrm_primary_id as copy_contact_id,
1286 r1.addressee as copy_addressee,
1287 r1.addressee_id as copy_addressee_id,
1288 r1.postal_greeting as copy_postal_greeting,
1289 r1.postal_greeting_id as copy_postal_greeting_id,
1291 r2.civicrm_primary_id as master_contact_id,
1292 r2.postal_greeting as master_postal_greeting,
1293 r2.postal_greeting_id as master_postal_greeting_id,
1294 r2.addressee as master_addressee,
1295 r2.addressee_id as master_addressee_id
1297 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1298 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1300 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1302 // find all the records that have the same street address BUT not in a household
1303 // require match on city and state as well
1305 SELECT r1.id as master_id,
1306 r1.civicrm_primary_id as master_contact_id,
1307 r1.postal_greeting as master_postal_greeting,
1308 r1.postal_greeting_id as master_postal_greeting_id,
1309 r1.addressee as master_addressee,
1310 r1.addressee_id as master_addressee_id,
1312 r2.civicrm_primary_id as copy_contact_id,
1313 r2.postal_greeting as copy_postal_greeting,
1314 r2.postal_greeting_id as copy_postal_greeting_id,
1315 r2.addressee as copy_addressee,
1316 r2.addressee_id as copy_addressee_id
1318 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1319 r1.city = r2.city AND
1320 r1.state_province_id = r2.state_province_id )
1321 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1322 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1323 AND ( r1.street_address != '' )
1327 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1329 // unset ids from $merge already present in $linkedMerge
1330 foreach ($linkedMerge as $masterID => $values) {
1331 $keys = array($masterID);
1332 $keys = array_merge($keys, array_keys($values['copy']));
1333 foreach ($merge as $mid => $vals) {
1334 if (in_array($mid, $keys)) {
1335 unset($merge[$mid]);
1338 foreach ($values['copy'] as $copyId) {
1339 if (in_array($copyId, $keys)) {
1340 unset($merge[$mid]['copy'][$copyId]);
1346 $merge = $merge +
$linkedMerge;
1348 foreach ($merge as $masterID => $values) {
1351 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1355 1 => array($values['addressee'], 'String'),
1356 2 => array($values['postalGreeting'], 'String'),
1357 3 => array($values['emailGreeting'], 'String'),
1358 4 => array($masterID, 'Integer'),
1360 CRM_Core_DAO
::executeQuery($sql, $params);
1362 // delete all copies
1363 $deleteIDs = array_keys($values['copy']);
1364 $deleteIDString = implode(',', $deleteIDs);
1366 DELETE FROM $tableName
1367 WHERE id IN ( $deleteIDString )
1369 CRM_Core_DAO
::executeQuery($sql);
1372 // unset temporary columns that were added for postal mailing format
1373 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1374 $unsetKeys = array_keys($sqlColumns);
1375 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1376 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1377 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1384 * @param int $contactId
1385 * @param array $exportParams
1389 public static function _replaceMergeTokens($contactId, $exportParams) {
1390 $greetings = array();
1393 $greetingFields = array(
1397 foreach ($greetingFields as $greeting) {
1398 if (!empty($exportParams[$greeting])) {
1399 $greetingLabel = $exportParams[$greeting];
1400 if (empty($contact)) {
1405 $contact = civicrm_api('contact', 'get', $values);
1407 if (!empty($contact['is_error'])) {
1410 $contact = $contact['values'][$contact['id']];
1413 $tokens = array('contact' => $greetingLabel);
1414 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1421 * The function unsets static part of the string, if token is the dynamic part.
1423 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1424 * i.e 'Hello Alan' => converted to => 'Alan'
1426 * @param string $parsedString
1427 * @param string $defaultGreeting
1428 * @param bool $addressMergeGreetings
1429 * @param string $greetingType
1433 public static function _trimNonTokens(
1434 &$parsedString, $defaultGreeting,
1435 $addressMergeGreetings, $greetingType = 'postal_greeting'
1437 if (!empty($addressMergeGreetings[$greetingType])) {
1438 $greetingLabel = $addressMergeGreetings[$greetingType];
1440 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1442 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1443 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1444 foreach ($stringsToBeReplaced as $key => $string) {
1445 // to keep one space
1446 $stringsToBeReplaced[$key] = ltrim($string);
1448 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1450 return $parsedString;
1455 * @param array $exportParams
1456 * @param bool $sharedAddress
1460 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1461 static $contactGreetingTokens = array();
1463 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1464 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1466 $merge = $parents = array();
1467 $dao = CRM_Core_DAO
::executeQuery($sql);
1469 while ($dao->fetch()) {
1470 $masterID = $dao->master_id
;
1471 $copyID = $dao->copy_id
;
1472 $masterPostalGreeting = $dao->master_postal_greeting
;
1473 $masterAddressee = $dao->master_addressee
;
1474 $copyAddressee = $dao->copy_addressee
;
1476 if (!$sharedAddress) {
1477 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1478 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1480 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1481 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1483 $masterAddressee = CRM_Utils_Array
::value('addressee',
1484 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1487 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1488 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1490 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1491 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1493 $copyAddressee = CRM_Utils_Array
::value('addressee',
1494 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1498 if (!isset($merge[$masterID])) {
1499 // check if this is an intermediate child
1500 // this happens if there are 3 or more matches a,b, c
1501 // the above query will return a, b / a, c / b, c
1502 // we might be doing a bit more work, but for now its ok, unless someone
1503 // knows how to fix the query above
1504 if (isset($parents[$masterID])) {
1505 $masterID = $parents[$masterID];
1508 $merge[$masterID] = array(
1509 'addressee' => $masterAddressee,
1511 'postalGreeting' => $masterPostalGreeting,
1513 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1516 $parents[$copyID] = $masterID;
1518 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1520 if (!empty($exportParams['postal_greeting_other']) &&
1521 count($merge[$masterID]['copy']) >= 1
1523 // use static greetings specified if no of contacts > 2
1524 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1526 elseif ($copyPostalGreeting) {
1527 self
::_trimNonTokens($copyPostalGreeting,
1528 $postalOptions[$dao->copy_postal_greeting_id
],
1531 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1532 // if there happens to be a duplicate, remove it
1533 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1536 if (!empty($exportParams['addressee_other']) &&
1537 count($merge[$masterID]['copy']) >= 1
1539 // use static greetings specified if no of contacts > 2
1540 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1542 elseif ($copyAddressee) {
1543 self
::_trimNonTokens($copyAddressee,
1544 $addresseeOptions[$dao->copy_addressee_id
],
1545 $exportParams, 'addressee'
1547 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1550 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1557 * Merge household record into the individual record
1560 * @param string $exportTempTable
1561 * Temporary temp table that stores the records.
1562 * @param array $headerRows
1563 * Array of headers for the export file.
1564 * @param array $sqlColumns
1565 * Array of names of the table columns of the temp table.
1566 * @param string $prefix
1567 * Name of the relationship type that is prefixed to the table columns.
1569 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1570 $prefixColumn = $prefix . '_';
1571 $allKeys = array_keys($sqlColumns);
1572 $replaced = array();
1573 $headerRows = array_values($headerRows);
1575 // name map of the non standard fields in header rows & sql columns
1576 $mappingFields = array(
1577 'civicrm_primary_id' => 'id',
1578 'contact_source' => 'source',
1579 'current_employer_id' => 'employer_id',
1580 'contact_is_deleted' => 'is_deleted',
1581 'name' => 'address_name',
1582 'provider_id' => 'im_service_provider',
1583 'phone_type_id' => 'phone_type',
1586 //figure out which columns are to be replaced by which ones
1587 foreach ($sqlColumns as $columnNames => $dontCare) {
1588 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1589 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1592 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1594 if (!empty($sqlColumns[$householdColName])) {
1595 $replaced[$columnNames] = $householdColName;
1599 $query = "UPDATE $exportTempTable SET ";
1602 foreach ($replaced as $from => $to) {
1603 $clause[] = "$from = $to ";
1604 unset($sqlColumns[$to]);
1605 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1606 unset($headerRows[$key]);
1609 $query .= implode(",\n", $clause);
1610 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1612 CRM_Core_DAO
::executeQuery($query);
1614 //drop the table columns that store redundant household info
1615 $dropQuery = "ALTER TABLE $exportTempTable ";
1616 foreach ($replaced as $householdColumns) {
1617 $dropClause[] = " DROP $householdColumns ";
1619 $dropQuery .= implode(",\n", $dropClause);
1621 CRM_Core_DAO
::executeQuery($dropQuery);
1623 // also drop the temp table if exists
1624 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1625 CRM_Core_DAO
::executeQuery($sql);
1627 // clean up duplicate records
1629 CREATE TABLE {$exportTempTable}_temp SELECT *
1630 FROM {$exportTempTable}
1631 GROUP BY civicrm_primary_id ";
1633 CRM_Core_DAO
::executeQuery($query);
1635 $query = "DROP TABLE $exportTempTable";
1636 CRM_Core_DAO
::executeQuery($query);
1638 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1639 CRM_Core_DAO
::executeQuery($query);
1643 * @param $exportTempTable
1644 * @param $headerRows
1645 * @param $sqlColumns
1646 * @param $exportMode
1647 * @param null $saveFile
1648 * @param string $batchItems
1650 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1651 $writeHeader = TRUE;
1653 $limit = self
::EXPORT_ROW_COUNT
;
1655 $query = "SELECT * FROM $exportTempTable";
1658 $limitQuery = $query . "
1659 LIMIT $offset, $limit
1661 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1667 $componentDetails = array();
1668 while ($dao->fetch()) {
1671 foreach ($sqlColumns as $column => $dontCare) {
1672 $row[$column] = $dao->$column;
1674 $componentDetails[] = $row;
1676 if ($exportMode == 'financial') {
1677 $getExportFileName = 'CiviCRM Contribution Search';
1680 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1682 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1689 if ($saveFile && !empty($csvRows)) {
1690 $batchItems .= $csvRows;
1693 $writeHeader = FALSE;
1699 * Manipulate header rows for relationship fields.
1701 * @param $headerRows
1703 public static function manipulateHeaderRows(&$headerRows) {
1704 foreach ($headerRows as & $header) {
1705 $split = explode('-', $header);
1706 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1707 $split[0] = $relationTypeName;
1708 $header = implode('-', $split);
1714 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1715 * or have no street address
1716 * @param $exportTempTable
1717 * @param $headerRows
1718 * @param $sqlColumns
1719 * @param $exportParams
1721 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1722 $whereClause = array();
1724 if (array_key_exists('is_deceased', $sqlColumns)) {
1725 $whereClause[] = 'is_deceased = 1';
1728 if (array_key_exists('do_not_mail', $sqlColumns)) {
1729 $whereClause[] = 'do_not_mail = 1';
1732 if (array_key_exists('street_address', $sqlColumns)) {
1733 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1735 // check for supplemental_address_1
1736 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1737 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1738 'address_options', TRUE, NULL, TRUE
1740 if (!empty($addressOptions['supplemental_address_1'])) {
1741 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1742 // enclose it again, since we are doing an AND in between a set of ORs
1743 $addressWhereClause = "( $addressWhereClause )";
1747 $whereClause[] = $addressWhereClause;
1750 if (!empty($whereClause)) {
1751 $whereClause = implode(' OR ', $whereClause);
1754 FROM $exportTempTable
1755 WHERE {$whereClause}";
1756 CRM_Core_DAO
::singleValueQuery($query);
1759 // unset temporary columns that were added for postal mailing format
1760 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1761 $unsetKeys = array_keys($sqlColumns);
1762 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1763 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1764 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1771 * Build componentPayment fields.
1773 public static function componentPaymentFields() {
1774 static $componentPaymentFields;
1775 if (!isset($componentPaymentFields)) {
1776 $componentPaymentFields = array(
1777 'componentPaymentField_total_amount' => ts('Total Amount'),
1778 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1779 'componentPaymentField_received_date' => ts('Date Received'),
1780 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1781 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1784 return $componentPaymentFields;
1788 * Set the definition for the header rows and sql columns based on the field to output.
1790 * @param string $field
1791 * @param array $headerRows
1792 * @param array $sqlColumns
1793 * Columns to go in the temp table.
1794 * @param \CRM_Export_BAO_ExportProcessor $processor
1795 * @param array|string $value
1796 * @param array $phoneTypes
1797 * @param array $imProviders
1798 * @param string $relationQuery
1799 * @param array $selectedPaymentFields
1802 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields) {
1804 $queryFields = $processor->getQueryFields();
1805 // Split campaign into 2 fields for id and title
1806 if (substr($field, -14) == 'campaign_title') {
1807 $headerRows[] = ts('Campaign Title');
1809 elseif (substr($field, -11) == 'campaign_id') {
1810 $headerRows[] = ts('Campaign ID');
1812 elseif (isset($queryFields[$field]['title'])) {
1813 $headerRows[] = $queryFields[$field]['title'];
1815 elseif ($field == 'phone_type_id') {
1816 $headerRows[] = ts('Phone Type');
1818 elseif ($field == 'provider_id') {
1819 $headerRows[] = ts('IM Service Provider');
1821 elseif (substr($field, 0, 5) == 'case_' && $queryFields['case'][$field]['title']) {
1822 $headerRows[] = $queryFields['case'][$field]['title'];
1824 elseif (array_key_exists($field, self
::$relationshipTypes)) {
1825 foreach ($value as $relationField => $relationValue) {
1826 // below block is same as primary block (duplicate)
1827 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
1828 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
1829 $headerName = $field . '-' . $relationField;
1832 if ($relationField == 'current_employer') {
1833 $headerName = $field . '-' . 'current_employer';
1836 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
1840 $headerRows[] = $headerName;
1842 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1844 elseif ($relationField == 'phone_type_id') {
1845 $headerName = $field . '-' . 'Phone Type';
1846 $headerRows[] = $headerName;
1847 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1849 elseif ($relationField == 'provider_id') {
1850 $headerName = $field . '-' . 'Im Service Provider';
1851 $headerRows[] = $headerName;
1852 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1854 elseif ($relationField == 'state_province_id') {
1855 $headerName = $field . '-' . 'state_province_id';
1856 $headerRows[] = $headerName;
1857 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1859 elseif (is_array($relationValue) && $relationField == 'location') {
1860 // fix header for location type case
1861 foreach ($relationValue as $ltype => $val) {
1862 foreach (array_keys($val) as $fld) {
1863 $type = explode('-', $fld);
1865 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
1867 if (!empty($type[1])) {
1868 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1869 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1871 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1872 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1875 $headerName = $field . '-' . $hdr;
1876 $headerRows[] = $headerName;
1877 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1882 self
::manipulateHeaderRows($headerRows);
1884 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1885 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1888 $headerRows[] = $field;
1891 self
::sqlColumnDefn($processor, $sqlColumns, $field);
1893 return array($headerRows, $sqlColumns);
1897 * Get the various arrays that we use to structure our output.
1899 * The extraction of these has been moved to a separate function for clarity and so that
1900 * tests can be added - in particular on the $outputHeaders array.
1902 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1903 * as a step on the refactoring path rather than how it should be.
1905 * @param array $returnProperties
1906 * @param \CRM_Export_BAO_ExportProcessor $processor
1907 * @param string $relationQuery
1908 * @param array $selectedPaymentFields
1910 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1911 * alias for the field generated by BAO_Query object.
1912 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1913 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1914 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1915 * I'm too embarassed to discuss here.
1917 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1918 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1919 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1920 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1921 * - a) the function used is more efficient or
1922 * - b) this code is old & outdated. Submit your answers to circular bin or better
1923 * yet find a way to comment them for posterity.
1925 public static function getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields) {
1926 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1927 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1928 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1930 $queryFields = $processor->getQueryFields();
1931 foreach ($returnProperties as $key => $value) {
1932 if ($key != 'location' ||
!is_array($value)) {
1933 $outputColumns[$key] = $value;
1934 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1937 foreach ($value as $locationType => $locationFields) {
1938 foreach (array_keys($locationFields) as $locationFieldName) {
1939 $type = explode('-', $locationFieldName);
1941 $actualDBFieldName = $type[0];
1942 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1943 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1945 if (!empty($type[1])) {
1946 $daoFieldName .= "-" . $type[1];
1947 if ($actualDBFieldName == 'phone') {
1948 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1950 elseif ($actualDBFieldName == 'im') {
1951 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1954 if ($type[0] == 'im_provider') {
1955 // Warning: shame inducing hack.
1956 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1958 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1959 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1960 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1961 $metadata[$daoFieldName] = array('context' => 'country');
1963 if ($actualDBFieldName == 'state_province') {
1964 $metadata[$daoFieldName] = array('context' => 'province');
1966 $outputColumns[$daoFieldName] = TRUE;
1971 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1975 * Get the values of linked household contact.
1977 * @param CRM_Core_DAO $relDAO
1978 * @param array $value
1979 * @param string $field
1982 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1983 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1984 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1985 $i18n = CRM_Core_I18n
::singleton();
1986 foreach ($value as $relationField => $relationValue) {
1987 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1988 $fieldValue = $relDAO->$relationField;
1989 if ($relationField == 'phone_type_id') {
1990 $fieldValue = $phoneTypes[$relationValue];
1992 elseif ($relationField == 'provider_id') {
1993 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1996 elseif (is_object($relDAO) && in_array($relationField, array(
2002 //special case for greeting replacement
2003 $fldValue = "{$relationField}_display";
2004 $fieldValue = $relDAO->$fldValue;
2007 elseif (is_object($relDAO) && $relationField == 'state_province') {
2008 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
2010 elseif (is_object($relDAO) && $relationField == 'country') {
2011 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
2016 $field = $field . '_';
2017 $relPrefix = $field . $relationField;
2019 if (is_object($relDAO) && $relationField == 'id') {
2020 $row[$relPrefix] = $relDAO->contact_id
;
2022 elseif (is_array($relationValue) && $relationField == 'location') {
2023 foreach ($relationValue as $ltype => $val) {
2024 foreach (array_keys($val) as $fld) {
2025 $type = explode('-', $fld);
2026 $fldValue = "{$ltype}-" . $type[0];
2027 if (!empty($type[1])) {
2028 $fldValue .= "-" . $type[1];
2030 // CRM-3157: localise country, region (both have ‘country’ context)
2031 // and state_province (‘province’ context)
2033 case (!is_object($relDAO)):
2034 $row[$field . '_' . $fldValue] = '';
2037 case in_array('country', $type):
2038 case in_array('world_region', $type):
2039 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2040 array('context' => 'country')
2044 case in_array('state_province', $type):
2045 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2046 array('context' => 'province')
2051 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2057 elseif (isset($fieldValue) && $fieldValue != '') {
2058 //check for custom data
2059 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
2060 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2063 //normal relationship fields
2064 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2065 switch ($relationField) {
2067 case 'world_region':
2068 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
2071 case 'state_province':
2072 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
2076 $row[$relPrefix] = $fieldValue;
2082 // if relation field is empty or null
2083 $row[$relPrefix] = '';
2089 * Get the ids that we want to get related contact details for.
2092 * @param int $exportMode
2096 protected static function getIDsForRelatedContact($ids, $exportMode) {
2097 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
2100 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
2102 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
2103 $dao = CRM_Core_DAO
::executeQuery("
2104 SELECT contact_id FROM civicrm_activity_contact
2105 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
2106 record_type_id = {$sourceID}
2109 while ($dao->fetch()) {
2110 $relIDs[] = $dao->contact_id
;
2114 $component = self
::exportComponent($exportMode);
2116 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
2117 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
2120 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
2127 * @param $exportMode
2128 * @param $componentTable
2129 * @param $returnProperties
2133 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode) {
2134 $allRelContactArray = $relationQuery = array();
2136 foreach (self
::$relationshipTypes as $rel => $dnt) {
2137 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
2138 $allRelContactArray[$rel] = array();
2139 // build Query for each relationship
2140 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
2141 NULL, FALSE, FALSE, $queryMode
2143 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
2145 list($id, $direction) = explode('_', $rel, 2);
2146 // identify the relationship direction
2147 $contactA = 'contact_id_a';
2148 $contactB = 'contact_id_b';
2149 if ($direction == 'b_a') {
2150 $contactA = 'contact_id_b';
2151 $contactB = 'contact_id_a';
2153 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
2155 $relationshipJoin = $relationshipClause = '';
2156 if (!$selectAll && $componentTable) {
2157 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
2159 elseif (!empty($relIDs)) {
2160 $relID = implode(',', $relIDs);
2161 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
2164 $relationFrom = " {$relationFrom}
2165 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
2166 {$relationshipJoin} ";
2168 //check for active relationship status only
2169 $today = date('Ymd');
2170 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
2171 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
2172 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
2173 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
2174 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
2176 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
2177 while ($allRelContactDAO->fetch()) {
2178 //FIX Me: Migrate this to table rather than array
2179 // build the array of all related contacts
2180 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
2182 $allRelContactDAO->free();
2185 return array($relationQuery, $allRelContactArray);