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';
274 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
275 $paymentFields = TRUE;
276 $paymentTableId = 'membership_id';
279 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
280 $paymentFields = TRUE;
281 $paymentTableId = 'pledge_payment_id';
284 case CRM_Contact_BAO_Query
::MODE_CASE
:
285 $paymentFields = FALSE;
286 $paymentTableId = '';
290 $paymentFields = FALSE;
291 $paymentTableId = '';
293 $extraProperties = array(
294 'paymentFields' => $paymentFields,
295 'paymentTableId' => $paymentTableId,
297 return $extraProperties;
301 * Get the list the export fields.
303 * @param int $selectAll
304 * User preference while export.
307 * @param array $params
308 * Associated array of fields.
309 * @param string $order
311 * @param array $fields
312 * Associated array of fields.
313 * @param array $moreReturnProperties
314 * Additional return fields.
315 * @param int $exportMode
317 * @param string $componentClause
319 * @param string $componentTable
321 * @param bool $mergeSameAddress
322 * Merge records if they have same address.
323 * @param bool $mergeSameHousehold
324 * Merge records if they belong to the same household.
326 * @param array $exportParams
327 * @param string $queryOperator
330 * An array can be requested from within a unit test.
332 * @throws \CRM_Core_Exception
334 public static function exportComponents(
340 $moreReturnProperties = NULL,
341 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
342 $componentClause = NULL,
343 $componentTable = NULL,
344 $mergeSameAddress = FALSE,
345 $mergeSameHousehold = FALSE,
346 $exportParams = array(),
347 $queryOperator = 'AND'
350 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $queryOperator);
351 $returnProperties = array();
352 $paymentFields = $selectedPaymentFields = $paymentTableId = FALSE;
354 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
355 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
356 // without manually testing the export of IM provider still works.
357 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
358 self
::$relationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
367 //also merge Head of Household
368 self
::$memberOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Household Member of', self
::$relationshipTypes);
369 self
::$headOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Head of Household for', self
::$relationshipTypes);
371 $queryMode = $processor->getQueryMode();
374 //construct return properties
375 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
376 $locationTypeFields = array(
378 'supplemental_address_1',
379 'supplemental_address_2',
380 'supplemental_address_3',
383 'postal_code_suffix',
393 foreach ($fields as $key => $value) {
394 $fieldName = CRM_Utils_Array
::value(1, $value);
399 if (array_key_exists($fieldName, self
::$relationshipTypes) && (!empty($value[2]) ||
!empty($value[4]))) {
400 self
::setRelationshipReturnProperties($value, $locationTypeFields, $fieldName);
401 // @todo we can later not add this to this array but maintain a separate array.
402 $returnProperties = array_merge($returnProperties, self
::$relationshipReturnProperties);
404 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
405 $locTypeId = $value[2];
406 if ($fieldName == 'phone') {
407 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
409 elseif ($fieldName == 'im') {
410 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
413 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
417 //hack to fix component fields
418 //revert mix of event_id and title
419 if ($fieldName == 'event_id') {
420 $returnProperties['event_id'] = 1;
423 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
424 array_key_exists($fieldName, self
::componentPaymentFields())
426 $selectedPaymentFields = TRUE;
427 $paymentTableId = 'participant_id';
428 $returnProperties[$fieldName] = 1;
431 $returnProperties[$fieldName] = 1;
435 $defaultExportMode = self
::defaultReturnProperty($exportMode);
436 if ($defaultExportMode) {
437 $returnProperties[$defaultExportMode] = 1;
441 $returnProperties = [];
442 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
443 foreach ($fields as $key => $var) {
444 if ($key && (substr($key, 0, 6) != 'custom')) {
446 $returnProperties[$key] = 1;
450 $extraProperties = self
::defineExtraProperties($queryMode);
451 $paymentFields = $extraProperties['paymentFields'];
452 $paymentTableId = $extraProperties['paymentTableId'];
454 $returnProperties = array_merge($returnProperties, $processor->getAdditionalReturnProperties());
456 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
457 // unset non exportable fields for components
458 $nonExpoFields = array(
462 'contribution_status_id',
464 'pledge_payment_status_id',
466 foreach ($nonExpoFields as $value) {
467 unset($returnProperties[$value]);
472 if ($mergeSameAddress) {
473 //make sure the addressee fields are selected
474 //while using merge same address feature
475 $returnProperties['addressee'] = 1;
476 $returnProperties['postal_greeting'] = 1;
477 $returnProperties['email_greeting'] = 1;
478 $returnProperties['street_name'] = 1;
479 $returnProperties['household_name'] = 1;
480 $returnProperties['street_address'] = 1;
481 $returnProperties['city'] = 1;
482 $returnProperties['state_province'] = 1;
484 // some columns are required for assistance incase they are not already present
485 $exportParams['merge_same_address']['temp_columns'] = array();
486 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
487 foreach ($tempColumns as $column) {
488 if (!array_key_exists($column, $returnProperties)) {
489 $returnProperties[$column] = 1;
490 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
491 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
496 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
497 // If an Additional Group is selected, then all contacts in that group are
498 // added to the export set (filtering out duplicates).
500 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";
501 CRM_Core_DAO
::executeQuery($query);
504 if ($moreReturnProperties) {
506 if (!empty($moreReturnProperties['group'])) {
507 unset($moreReturnProperties['group']);
508 $moreReturnProperties['groups'] = 1;
510 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
513 $exportParams['postal_mailing_export']['temp_columns'] = array();
514 if ($exportParams['exportOption'] == 2 &&
515 isset($exportParams['postal_mailing_export']) &&
516 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
518 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
519 foreach ($postalColumns as $column) {
520 if (!array_key_exists($column, $returnProperties)) {
521 $returnProperties[$column] = 1;
522 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
527 // rectify params to what proximity search expects if there is a value for prox_distance
529 if (!empty($params)) {
530 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
533 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
535 if ($mergeSameHousehold == 1) {
536 if (empty($returnProperties['id'])) {
537 $returnProperties['id'] = 1;
540 foreach ($returnProperties as $key => $value) {
541 if (!array_key_exists($key, self
::$relationshipTypes)) {
542 $returnProperties[self
::$memberOfHouseholdRelationshipKey][$key] = $value;
543 $returnProperties[self
::$headOfHouseholdRelationshipKey][$key] = $value;
547 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['location_type']);
548 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['im_provider']);
549 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['location_type']);
550 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['im_provider']);
553 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode);
555 // make sure the groups stuff is included only if specifically specified
556 // by the fields param (CRM-1969), else we limit the contacts outputted to only
557 // ones that are part of a group
558 if (!empty($returnProperties['groups'])) {
559 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
560 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
561 // total hack for export, CRM-3618
562 $from = str_replace($oldClause,
568 if (!$selectAll && $componentTable) {
569 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
571 elseif ($componentClause) {
573 $where = "WHERE $componentClause";
576 $where .= " AND $componentClause";
580 // CRM-13982 - check if is deleted
581 $excludeTrashed = TRUE;
582 foreach ($params as $value) {
583 if ($value[0] == 'contact_is_deleted') {
584 $excludeTrashed = FALSE;
587 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
590 $where = "WHERE $trashClause";
593 $where .= " AND $trashClause";
596 $queryString = "$select $from $where $having";
598 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
600 $queryString .= $groupBy;
603 // always add contact_a.id to the ORDER clause
604 // so the order is deterministic
606 if (strpos('contact_a.id', $order) === FALSE) {
607 $order .= ", contact_a.id";
610 list($field, $dir) = explode(' ', $order, 2);
611 $field = trim($field);
612 if (!empty($returnProperties[$field])) {
614 $queryString .= " ORDER BY $order";
618 $addPaymentHeader = FALSE;
620 $paymentDetails = array();
621 if ($paymentFields ||
$selectedPaymentFields) {
623 // get payment related in for event and members
624 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
625 //get all payment headers.
626 // If we haven't selected specific payment fields, load in all the
628 if (!$selectedPaymentFields) {
629 $paymentHeaders = self
::componentPaymentFields();
630 if (!empty($paymentDetails)) {
631 $addPaymentHeader = TRUE;
634 // If we have selected specific payment fields, leave the payment headers
635 // as an empty array; the headers for each selected field will be added
638 $paymentHeaders = array();
640 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
643 $componentDetails = array();
646 $rowCount = self
::EXPORT_ROW_COUNT
;
648 // we write to temp table often to avoid using too much memory
653 // for CRM-3157 purposes
654 $i18n = CRM_Core_I18n
::singleton();
656 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields);
658 $limitReached = FALSE;
659 while (!$limitReached) {
660 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
661 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
662 // If this is less than our limit by the end of the iteration we do not need to run the query again to
663 // check if some remain.
664 $rowsThisIteration = 0;
666 while ($iterationDAO->fetch()) {
668 $rowsThisIteration++
;
670 $query->convertToPseudoNames($iterationDAO);
672 //first loop through output columns so that we return what is required, and in same order.
673 foreach ($outputColumns as $field => $value) {
675 // add im_provider to $dao object
676 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
677 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
680 //build row values (data)
682 if (property_exists($iterationDAO, $field)) {
683 $fieldValue = $iterationDAO->$field;
684 // to get phone type from phone type id
685 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
686 $fieldValue = $phoneTypes[$fieldValue];
688 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
689 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
691 elseif (strstr($field, 'master_id')) {
692 $masterAddressId = NULL;
693 if (isset($iterationDAO->$field)) {
694 $masterAddressId = $iterationDAO->$field;
696 // get display name of contact that address is shared.
697 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
701 if (array_key_exists($field, self
::$relationshipTypes)) {
702 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
703 $relationQuery[$field]->convertToPseudoNames($relDAO);
704 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
707 $row[$field] = self
::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId);
711 // add payment headers if required
712 if ($addPaymentHeader && $paymentFields) {
713 // @todo rather than do this for every single row do it before the loop starts.
714 // where other header definitions take place.
715 $headerRows = array_merge($headerRows, $paymentHeaders);
716 foreach (array_keys($paymentHeaders) as $paymentHdr) {
717 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
722 $exportTempTable = self
::createTempTable($sqlColumns);
725 //build header only once
728 // If specific payment fields have been selected for export, payment
729 // data will already be in $row. Otherwise, add payment related
730 // information, if appropriate.
731 if ($addPaymentHeader) {
732 if (!$selectedPaymentFields) {
733 if ($paymentFields) {
734 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
735 if (!is_array($paymentData) ||
empty($paymentData)) {
736 $paymentData = $nullContributionDetails;
738 $row = array_merge($row, $paymentData);
740 elseif (!empty($paymentDetails)) {
741 $row = array_merge($row, $nullContributionDetails);
745 //remove organization name for individuals if it is set for current employer
746 if (!empty($row['contact_type']) &&
747 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
749 $row['organization_name'] = '';
752 // add component info
753 // write the row to a file
754 $componentDetails[] = $row;
756 // output every $tempRowCount rows
757 if ($count %
$tempRowCount == 0) {
758 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
759 $componentDetails = array();
762 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
763 $limitReached = TRUE;
765 $offset +
= $rowCount;
768 if ($exportTempTable) {
769 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
771 // if postalMailing option is checked, exclude contacts who are deceased, have
772 // "Do not mail" privacy setting, or have no street address
773 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
774 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
776 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
779 // do merge same address and merge same household processing
780 if ($mergeSameAddress) {
781 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
784 // merge the records if they have corresponding households
785 if ($mergeSameHousehold) {
786 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$memberOfHouseholdRelationshipKey);
787 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$headOfHouseholdRelationshipKey);
791 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
793 // In order to be able to write a unit test against this function we need to suppress
794 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
795 if (empty($exportParams['suppress_csv_for_testing'])) {
796 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
799 // return tableName and sqlColumns in test context
800 return array($exportTempTable, $sqlColumns);
803 // delete the export temp table and component table
804 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
805 CRM_Core_DAO
::executeQuery($sql);
806 CRM_Core_DAO
::reenableFullGroupByMode();
807 CRM_Utils_System
::civiExit();
810 CRM_Core_DAO
::reenableFullGroupByMode();
811 throw new CRM_Core_Exception(ts('No records to export'));
816 * Name of the export file based on mode.
818 * @param string $output
826 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
828 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
829 return ts('CiviCRM Contact Search');
831 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
832 return ts('CiviCRM Contribution Search');
834 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
835 return ts('CiviCRM Member Search');
837 case CRM_Export_Form_Select
::EVENT_EXPORT
:
838 return ts('CiviCRM Participant Search');
840 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
841 return ts('CiviCRM Pledge Search');
843 case CRM_Export_Form_Select
::CASE_EXPORT
:
844 return ts('CiviCRM Case Search');
846 case CRM_Export_Form_Select
::GRANT_EXPORT
:
847 return ts('CiviCRM Grant Search');
849 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
850 return ts('CiviCRM Activity Search');
855 * Handle import error file creation.
857 public static function invoke() {
858 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
859 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
860 if (empty($parserName) ||
empty($type)) {
864 // clean and ensure parserName is a valid string
865 $parserName = CRM_Utils_String
::munge($parserName);
866 $parserClass = explode('_', $parserName);
868 // make sure parserClass is in the CRM namespace and
869 // at least 3 levels deep
870 if ($parserClass[0] == 'CRM' &&
871 count($parserClass) >= 3
873 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
874 // ensure the functions exists
875 if (method_exists($parserName, 'errorFileName') &&
876 method_exists($parserName, 'saveFileName')
878 $errorFileName = $parserName::errorFileName($type);
879 $saveFileName = $parserName::saveFileName($type);
880 if (!empty($errorFileName) && !empty($saveFileName)) {
881 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
882 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
883 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
884 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
885 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
887 readfile($errorFileName);
891 CRM_Utils_System
::civiExit();
895 * @param $customSearchClass
899 public static function exportCustom($customSearchClass, $formValues, $order) {
900 $ext = CRM_Extension_System
::singleton()->getMapper();
901 if (!$ext->isExtensionClass($customSearchClass)) {
902 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
905 require_once $ext->classToPath($customSearchClass);
907 $search = new $customSearchClass($formValues);
909 $includeContactIDs = FALSE;
910 if ($formValues['radio_ts'] == 'ts_sel') {
911 $includeContactIDs = TRUE;
914 $sql = $search->all(0, 0, $order, $includeContactIDs);
916 $columns = $search->columns();
918 $header = array_keys($columns);
919 $fields = array_values($columns);
922 $dao = CRM_Core_DAO
::executeQuery($sql);
924 if (method_exists($search, 'alterRow')) {
927 while ($dao->fetch()) {
930 foreach ($fields as $field) {
931 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
932 $row[$field] = $dao->$unqualified_field;
935 $search->alterRow($row);
940 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
941 CRM_Utils_System
::civiExit();
945 * @param \CRM_Export_BAO_ExportProcessor $processor
949 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
950 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
953 $queryFields = $processor->getQueryFields();
955 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
956 if ($fieldName == 'id') {
957 $fieldName = 'civicrm_primary_id';
960 // early exit for master_id, CRM-12100
961 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
962 // also for current_employer, CRM-16939
963 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
964 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
968 if (substr($fieldName, -11) == 'campaign_id') {
970 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
974 $lookUp = array('prefix_id', 'suffix_id');
975 // set the sql columns
976 if (isset($queryFields[$field]['type'])) {
977 switch ($queryFields[$field]['type']) {
978 case CRM_Utils_Type
::T_INT
:
979 case CRM_Utils_Type
::T_BOOLEAN
:
980 if (in_array($field, $lookUp)) {
981 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
984 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
988 case CRM_Utils_Type
::T_STRING
:
989 if (isset($queryFields[$field]['maxlength'])) {
990 $sqlColumns[$fieldName] = "$fieldName varchar({$queryFields[$field]['maxlength']})";
993 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
997 case CRM_Utils_Type
::T_TEXT
:
998 case CRM_Utils_Type
::T_LONGTEXT
:
999 case CRM_Utils_Type
::T_BLOB
:
1000 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1001 $sqlColumns[$fieldName] = "$fieldName longtext";
1004 case CRM_Utils_Type
::T_FLOAT
:
1005 case CRM_Utils_Type
::T_ENUM
:
1006 case CRM_Utils_Type
::T_DATE
:
1007 case CRM_Utils_Type
::T_TIME
:
1008 case CRM_Utils_Type
::T_TIMESTAMP
:
1009 case CRM_Utils_Type
::T_MONEY
:
1010 case CRM_Utils_Type
::T_EMAIL
:
1011 case CRM_Utils_Type
::T_URL
:
1012 case CRM_Utils_Type
::T_CCNUM
:
1014 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1019 if (substr($fieldName, -3, 3) == '_id') {
1020 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1022 elseif (substr($fieldName, -5, 5) == '_note') {
1023 $sqlColumns[$fieldName] = "$fieldName text";
1026 $changeFields = array(
1032 if (in_array($fieldName, $changeFields)) {
1033 $sqlColumns[$fieldName] = "$fieldName text";
1036 // set the sql columns for custom data
1037 if (isset($queryFields[$field]['data_type'])) {
1039 switch ($queryFields[$field]['data_type']) {
1041 // May be option labels, which could be up to 512 characters
1042 $length = max(512, CRM_Utils_Array
::value('text_length', $queryFields[$field]));
1043 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1047 case 'StateProvince':
1049 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1053 $sqlColumns[$fieldName] = "$fieldName text";
1057 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1062 $sqlColumns[$fieldName] = "$fieldName text";
1070 * @param string $tableName
1072 * @param $sqlColumns
1074 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1075 if (empty($details)) {
1084 $id = CRM_Core_DAO
::singleValueQuery($sql);
1089 $sqlClause = array();
1091 foreach ($details as $dontCare => $row) {
1093 $valueString = array($id);
1094 foreach ($row as $dontCare => $value) {
1095 if (empty($value)) {
1096 $valueString[] = "''";
1099 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1102 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1105 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1107 $sqlValueString = implode(",\n", $sqlClause);
1110 INSERT INTO $tableName $sqlColumnString
1111 VALUES $sqlValueString
1113 CRM_Core_DAO
::executeQuery($sql);
1117 * @param $sqlColumns
1121 public static function createTempTable(&$sqlColumns) {
1122 //creating a temporary table for the search result that need be exported
1123 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
1125 // also create the sql table
1126 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1127 CRM_Core_DAO
::executeQuery($sql);
1130 CREATE TABLE {$exportTempTable} (
1131 id int unsigned NOT NULL AUTO_INCREMENT,
1133 $sql .= implode(",\n", array_values($sqlColumns));
1138 // add indexes for street_address and household_name if present
1139 $addIndices = array(
1142 'civicrm_primary_id',
1145 foreach ($addIndices as $index) {
1146 if (isset($sqlColumns[$index])) {
1148 INDEX index_{$index}( $index )
1154 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1157 CRM_Core_DAO
::executeQuery($sql);
1158 return $exportTempTable;
1162 * @param string $tableName
1163 * @param $headerRows
1164 * @param $sqlColumns
1165 * @param array $exportParams
1167 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1168 // check if any records are present based on if they have used shared address feature,
1169 // and not based on if city / state .. matches.
1171 SELECT r1.id as copy_id,
1172 r1.civicrm_primary_id as copy_contact_id,
1173 r1.addressee as copy_addressee,
1174 r1.addressee_id as copy_addressee_id,
1175 r1.postal_greeting as copy_postal_greeting,
1176 r1.postal_greeting_id as copy_postal_greeting_id,
1178 r2.civicrm_primary_id as master_contact_id,
1179 r2.postal_greeting as master_postal_greeting,
1180 r2.postal_greeting_id as master_postal_greeting_id,
1181 r2.addressee as master_addressee,
1182 r2.addressee_id as master_addressee_id
1184 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1185 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1187 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1189 // find all the records that have the same street address BUT not in a household
1190 // require match on city and state as well
1192 SELECT r1.id as master_id,
1193 r1.civicrm_primary_id as master_contact_id,
1194 r1.postal_greeting as master_postal_greeting,
1195 r1.postal_greeting_id as master_postal_greeting_id,
1196 r1.addressee as master_addressee,
1197 r1.addressee_id as master_addressee_id,
1199 r2.civicrm_primary_id as copy_contact_id,
1200 r2.postal_greeting as copy_postal_greeting,
1201 r2.postal_greeting_id as copy_postal_greeting_id,
1202 r2.addressee as copy_addressee,
1203 r2.addressee_id as copy_addressee_id
1205 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1206 r1.city = r2.city AND
1207 r1.state_province_id = r2.state_province_id )
1208 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1209 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1210 AND ( r1.street_address != '' )
1214 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1216 // unset ids from $merge already present in $linkedMerge
1217 foreach ($linkedMerge as $masterID => $values) {
1218 $keys = array($masterID);
1219 $keys = array_merge($keys, array_keys($values['copy']));
1220 foreach ($merge as $mid => $vals) {
1221 if (in_array($mid, $keys)) {
1222 unset($merge[$mid]);
1225 foreach ($values['copy'] as $copyId) {
1226 if (in_array($copyId, $keys)) {
1227 unset($merge[$mid]['copy'][$copyId]);
1233 $merge = $merge +
$linkedMerge;
1235 foreach ($merge as $masterID => $values) {
1238 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1242 1 => array($values['addressee'], 'String'),
1243 2 => array($values['postalGreeting'], 'String'),
1244 3 => array($values['emailGreeting'], 'String'),
1245 4 => array($masterID, 'Integer'),
1247 CRM_Core_DAO
::executeQuery($sql, $params);
1249 // delete all copies
1250 $deleteIDs = array_keys($values['copy']);
1251 $deleteIDString = implode(',', $deleteIDs);
1253 DELETE FROM $tableName
1254 WHERE id IN ( $deleteIDString )
1256 CRM_Core_DAO
::executeQuery($sql);
1259 // unset temporary columns that were added for postal mailing format
1260 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1261 $unsetKeys = array_keys($sqlColumns);
1262 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1263 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1264 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1271 * @param int $contactId
1272 * @param array $exportParams
1276 public static function _replaceMergeTokens($contactId, $exportParams) {
1277 $greetings = array();
1280 $greetingFields = array(
1284 foreach ($greetingFields as $greeting) {
1285 if (!empty($exportParams[$greeting])) {
1286 $greetingLabel = $exportParams[$greeting];
1287 if (empty($contact)) {
1292 $contact = civicrm_api('contact', 'get', $values);
1294 if (!empty($contact['is_error'])) {
1297 $contact = $contact['values'][$contact['id']];
1300 $tokens = array('contact' => $greetingLabel);
1301 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1308 * The function unsets static part of the string, if token is the dynamic part.
1310 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1311 * i.e 'Hello Alan' => converted to => 'Alan'
1313 * @param string $parsedString
1314 * @param string $defaultGreeting
1315 * @param bool $addressMergeGreetings
1316 * @param string $greetingType
1320 public static function _trimNonTokens(
1321 &$parsedString, $defaultGreeting,
1322 $addressMergeGreetings, $greetingType = 'postal_greeting'
1324 if (!empty($addressMergeGreetings[$greetingType])) {
1325 $greetingLabel = $addressMergeGreetings[$greetingType];
1327 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1329 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1330 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1331 foreach ($stringsToBeReplaced as $key => $string) {
1332 // to keep one space
1333 $stringsToBeReplaced[$key] = ltrim($string);
1335 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1337 return $parsedString;
1342 * @param array $exportParams
1343 * @param bool $sharedAddress
1347 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1348 static $contactGreetingTokens = array();
1350 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1351 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1353 $merge = $parents = array();
1354 $dao = CRM_Core_DAO
::executeQuery($sql);
1356 while ($dao->fetch()) {
1357 $masterID = $dao->master_id
;
1358 $copyID = $dao->copy_id
;
1359 $masterPostalGreeting = $dao->master_postal_greeting
;
1360 $masterAddressee = $dao->master_addressee
;
1361 $copyAddressee = $dao->copy_addressee
;
1363 if (!$sharedAddress) {
1364 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1365 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1367 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1368 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1370 $masterAddressee = CRM_Utils_Array
::value('addressee',
1371 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1374 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1375 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1377 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1378 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1380 $copyAddressee = CRM_Utils_Array
::value('addressee',
1381 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1385 if (!isset($merge[$masterID])) {
1386 // check if this is an intermediate child
1387 // this happens if there are 3 or more matches a,b, c
1388 // the above query will return a, b / a, c / b, c
1389 // we might be doing a bit more work, but for now its ok, unless someone
1390 // knows how to fix the query above
1391 if (isset($parents[$masterID])) {
1392 $masterID = $parents[$masterID];
1395 $merge[$masterID] = array(
1396 'addressee' => $masterAddressee,
1398 'postalGreeting' => $masterPostalGreeting,
1400 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1403 $parents[$copyID] = $masterID;
1405 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1407 if (!empty($exportParams['postal_greeting_other']) &&
1408 count($merge[$masterID]['copy']) >= 1
1410 // use static greetings specified if no of contacts > 2
1411 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1413 elseif ($copyPostalGreeting) {
1414 self
::_trimNonTokens($copyPostalGreeting,
1415 $postalOptions[$dao->copy_postal_greeting_id
],
1418 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1419 // if there happens to be a duplicate, remove it
1420 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1423 if (!empty($exportParams['addressee_other']) &&
1424 count($merge[$masterID]['copy']) >= 1
1426 // use static greetings specified if no of contacts > 2
1427 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1429 elseif ($copyAddressee) {
1430 self
::_trimNonTokens($copyAddressee,
1431 $addresseeOptions[$dao->copy_addressee_id
],
1432 $exportParams, 'addressee'
1434 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1437 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1444 * Merge household record into the individual record
1447 * @param string $exportTempTable
1448 * Temporary temp table that stores the records.
1449 * @param array $headerRows
1450 * Array of headers for the export file.
1451 * @param array $sqlColumns
1452 * Array of names of the table columns of the temp table.
1453 * @param string $prefix
1454 * Name of the relationship type that is prefixed to the table columns.
1456 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1457 $prefixColumn = $prefix . '_';
1458 $allKeys = array_keys($sqlColumns);
1459 $replaced = array();
1460 $headerRows = array_values($headerRows);
1462 // name map of the non standard fields in header rows & sql columns
1463 $mappingFields = array(
1464 'civicrm_primary_id' => 'id',
1465 'contact_source' => 'source',
1466 'current_employer_id' => 'employer_id',
1467 'contact_is_deleted' => 'is_deleted',
1468 'name' => 'address_name',
1469 'provider_id' => 'im_service_provider',
1470 'phone_type_id' => 'phone_type',
1473 //figure out which columns are to be replaced by which ones
1474 foreach ($sqlColumns as $columnNames => $dontCare) {
1475 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1476 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1479 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1481 if (!empty($sqlColumns[$householdColName])) {
1482 $replaced[$columnNames] = $householdColName;
1486 $query = "UPDATE $exportTempTable SET ";
1489 foreach ($replaced as $from => $to) {
1490 $clause[] = "$from = $to ";
1491 unset($sqlColumns[$to]);
1492 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1493 unset($headerRows[$key]);
1496 $query .= implode(",\n", $clause);
1497 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1499 CRM_Core_DAO
::executeQuery($query);
1501 //drop the table columns that store redundant household info
1502 $dropQuery = "ALTER TABLE $exportTempTable ";
1503 foreach ($replaced as $householdColumns) {
1504 $dropClause[] = " DROP $householdColumns ";
1506 $dropQuery .= implode(",\n", $dropClause);
1508 CRM_Core_DAO
::executeQuery($dropQuery);
1510 // also drop the temp table if exists
1511 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1512 CRM_Core_DAO
::executeQuery($sql);
1514 // clean up duplicate records
1516 CREATE TABLE {$exportTempTable}_temp SELECT *
1517 FROM {$exportTempTable}
1518 GROUP BY civicrm_primary_id ";
1520 CRM_Core_DAO
::executeQuery($query);
1522 $query = "DROP TABLE $exportTempTable";
1523 CRM_Core_DAO
::executeQuery($query);
1525 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1526 CRM_Core_DAO
::executeQuery($query);
1530 * @param $exportTempTable
1531 * @param $headerRows
1532 * @param $sqlColumns
1533 * @param $exportMode
1534 * @param null $saveFile
1535 * @param string $batchItems
1537 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1538 $writeHeader = TRUE;
1540 $limit = self
::EXPORT_ROW_COUNT
;
1542 $query = "SELECT * FROM $exportTempTable";
1545 $limitQuery = $query . "
1546 LIMIT $offset, $limit
1548 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1554 $componentDetails = array();
1555 while ($dao->fetch()) {
1558 foreach ($sqlColumns as $column => $dontCare) {
1559 $row[$column] = $dao->$column;
1561 $componentDetails[] = $row;
1563 if ($exportMode == 'financial') {
1564 $getExportFileName = 'CiviCRM Contribution Search';
1567 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1569 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1576 if ($saveFile && !empty($csvRows)) {
1577 $batchItems .= $csvRows;
1580 $writeHeader = FALSE;
1586 * Manipulate header rows for relationship fields.
1588 * @param $headerRows
1590 public static function manipulateHeaderRows(&$headerRows) {
1591 foreach ($headerRows as & $header) {
1592 $split = explode('-', $header);
1593 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1594 $split[0] = $relationTypeName;
1595 $header = implode('-', $split);
1601 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1602 * or have no street address
1603 * @param $exportTempTable
1604 * @param $headerRows
1605 * @param $sqlColumns
1606 * @param $exportParams
1608 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1609 $whereClause = array();
1611 if (array_key_exists('is_deceased', $sqlColumns)) {
1612 $whereClause[] = 'is_deceased = 1';
1615 if (array_key_exists('do_not_mail', $sqlColumns)) {
1616 $whereClause[] = 'do_not_mail = 1';
1619 if (array_key_exists('street_address', $sqlColumns)) {
1620 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1622 // check for supplemental_address_1
1623 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1624 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1625 'address_options', TRUE, NULL, TRUE
1627 if (!empty($addressOptions['supplemental_address_1'])) {
1628 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1629 // enclose it again, since we are doing an AND in between a set of ORs
1630 $addressWhereClause = "( $addressWhereClause )";
1634 $whereClause[] = $addressWhereClause;
1637 if (!empty($whereClause)) {
1638 $whereClause = implode(' OR ', $whereClause);
1641 FROM $exportTempTable
1642 WHERE {$whereClause}";
1643 CRM_Core_DAO
::singleValueQuery($query);
1646 // unset temporary columns that were added for postal mailing format
1647 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1648 $unsetKeys = array_keys($sqlColumns);
1649 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1650 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1651 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1658 * Build componentPayment fields.
1660 public static function componentPaymentFields() {
1661 static $componentPaymentFields;
1662 if (!isset($componentPaymentFields)) {
1663 $componentPaymentFields = array(
1664 'componentPaymentField_total_amount' => ts('Total Amount'),
1665 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1666 'componentPaymentField_received_date' => ts('Date Received'),
1667 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1668 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1671 return $componentPaymentFields;
1675 * Set the definition for the header rows and sql columns based on the field to output.
1677 * @param string $field
1678 * @param array $headerRows
1679 * @param array $sqlColumns
1680 * Columns to go in the temp table.
1681 * @param \CRM_Export_BAO_ExportProcessor $processor
1682 * @param array|string $value
1683 * @param array $phoneTypes
1684 * @param array $imProviders
1685 * @param string $relationQuery
1686 * @param array $selectedPaymentFields
1689 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields) {
1691 $queryFields = $processor->getQueryFields();
1692 // Split campaign into 2 fields for id and title
1693 if (substr($field, -14) == 'campaign_title') {
1694 $headerRows[] = ts('Campaign Title');
1696 elseif (substr($field, -11) == 'campaign_id') {
1697 $headerRows[] = ts('Campaign ID');
1699 elseif (isset($queryFields[$field]['title'])) {
1700 $headerRows[] = $queryFields[$field]['title'];
1702 elseif ($field == 'phone_type_id') {
1703 $headerRows[] = ts('Phone Type');
1705 elseif ($field == 'provider_id') {
1706 $headerRows[] = ts('IM Service Provider');
1708 elseif (array_key_exists($field, self
::$relationshipTypes)) {
1709 foreach ($value as $relationField => $relationValue) {
1710 // below block is same as primary block (duplicate)
1711 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
1712 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
1713 $headerName = $field . '-' . $relationField;
1716 if ($relationField == 'current_employer') {
1717 $headerName = $field . '-' . 'current_employer';
1720 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
1724 $headerRows[] = $headerName;
1726 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1728 elseif ($relationField == 'phone_type_id') {
1729 $headerName = $field . '-' . 'Phone Type';
1730 $headerRows[] = $headerName;
1731 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1733 elseif ($relationField == 'provider_id') {
1734 $headerName = $field . '-' . 'Im Service Provider';
1735 $headerRows[] = $headerName;
1736 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1738 elseif ($relationField == 'state_province_id') {
1739 $headerName = $field . '-' . 'state_province_id';
1740 $headerRows[] = $headerName;
1741 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1743 elseif (is_array($relationValue) && $relationField == 'location') {
1744 // fix header for location type case
1745 foreach ($relationValue as $ltype => $val) {
1746 foreach (array_keys($val) as $fld) {
1747 $type = explode('-', $fld);
1749 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
1751 if (!empty($type[1])) {
1752 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1753 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1755 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1756 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1759 $headerName = $field . '-' . $hdr;
1760 $headerRows[] = $headerName;
1761 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1766 self
::manipulateHeaderRows($headerRows);
1768 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1769 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1772 $headerRows[] = $field;
1775 self
::sqlColumnDefn($processor, $sqlColumns, $field);
1777 return array($headerRows, $sqlColumns);
1781 * Get the various arrays that we use to structure our output.
1783 * The extraction of these has been moved to a separate function for clarity and so that
1784 * tests can be added - in particular on the $outputHeaders array.
1786 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1787 * as a step on the refactoring path rather than how it should be.
1789 * @param array $returnProperties
1790 * @param \CRM_Export_BAO_ExportProcessor $processor
1791 * @param string $relationQuery
1792 * @param array $selectedPaymentFields
1794 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1795 * alias for the field generated by BAO_Query object.
1796 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1797 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1798 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1799 * I'm too embarassed to discuss here.
1801 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1802 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1803 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1804 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1805 * - a) the function used is more efficient or
1806 * - b) this code is old & outdated. Submit your answers to circular bin or better
1807 * yet find a way to comment them for posterity.
1809 public static function getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields) {
1810 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1811 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1812 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1814 $queryFields = $processor->getQueryFields();
1815 foreach ($returnProperties as $key => $value) {
1816 if ($key != 'location' ||
!is_array($value)) {
1817 $outputColumns[$key] = $value;
1818 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1821 foreach ($value as $locationType => $locationFields) {
1822 foreach (array_keys($locationFields) as $locationFieldName) {
1823 $type = explode('-', $locationFieldName);
1825 $actualDBFieldName = $type[0];
1826 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1827 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1829 if (!empty($type[1])) {
1830 $daoFieldName .= "-" . $type[1];
1831 if ($actualDBFieldName == 'phone') {
1832 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1834 elseif ($actualDBFieldName == 'im') {
1835 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1838 if ($type[0] == 'im_provider') {
1839 // Warning: shame inducing hack.
1840 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1842 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1843 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1844 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1845 $metadata[$daoFieldName] = array('context' => 'country');
1847 if ($actualDBFieldName == 'state_province') {
1848 $metadata[$daoFieldName] = array('context' => 'province');
1850 $outputColumns[$daoFieldName] = TRUE;
1855 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1859 * Get the values of linked household contact.
1861 * @param CRM_Core_DAO $relDAO
1862 * @param array $value
1863 * @param string $field
1866 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1867 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1868 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1869 $i18n = CRM_Core_I18n
::singleton();
1870 foreach ($value as $relationField => $relationValue) {
1871 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1872 $fieldValue = $relDAO->$relationField;
1873 if ($relationField == 'phone_type_id') {
1874 $fieldValue = $phoneTypes[$relationValue];
1876 elseif ($relationField == 'provider_id') {
1877 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1880 elseif (is_object($relDAO) && in_array($relationField, array(
1886 //special case for greeting replacement
1887 $fldValue = "{$relationField}_display";
1888 $fieldValue = $relDAO->$fldValue;
1891 elseif (is_object($relDAO) && $relationField == 'state_province') {
1892 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1894 elseif (is_object($relDAO) && $relationField == 'country') {
1895 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1900 $field = $field . '_';
1901 $relPrefix = $field . $relationField;
1903 if (is_object($relDAO) && $relationField == 'id') {
1904 $row[$relPrefix] = $relDAO->contact_id
;
1906 elseif (is_array($relationValue) && $relationField == 'location') {
1907 foreach ($relationValue as $ltype => $val) {
1908 foreach (array_keys($val) as $fld) {
1909 $type = explode('-', $fld);
1910 $fldValue = "{$ltype}-" . $type[0];
1911 if (!empty($type[1])) {
1912 $fldValue .= "-" . $type[1];
1914 // CRM-3157: localise country, region (both have ‘country’ context)
1915 // and state_province (‘province’ context)
1917 case (!is_object($relDAO)):
1918 $row[$field . '_' . $fldValue] = '';
1921 case in_array('country', $type):
1922 case in_array('world_region', $type):
1923 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1924 array('context' => 'country')
1928 case in_array('state_province', $type):
1929 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1930 array('context' => 'province')
1935 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1941 elseif (isset($fieldValue) && $fieldValue != '') {
1942 //check for custom data
1943 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1944 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1947 //normal relationship fields
1948 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1949 switch ($relationField) {
1951 case 'world_region':
1952 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1955 case 'state_province':
1956 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1960 $row[$relPrefix] = $fieldValue;
1966 // if relation field is empty or null
1967 $row[$relPrefix] = '';
1973 * Get the ids that we want to get related contact details for.
1976 * @param int $exportMode
1980 protected static function getIDsForRelatedContact($ids, $exportMode) {
1981 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1984 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1986 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1987 $dao = CRM_Core_DAO
::executeQuery("
1988 SELECT contact_id FROM civicrm_activity_contact
1989 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1990 record_type_id = {$sourceID}
1993 while ($dao->fetch()) {
1994 $relIDs[] = $dao->contact_id
;
1998 $component = self
::exportComponent($exportMode);
2000 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
2001 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
2004 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
2011 * @param $exportMode
2012 * @param $componentTable
2013 * @param $returnProperties
2017 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode) {
2018 $allRelContactArray = $relationQuery = array();
2020 foreach (self
::$relationshipTypes as $rel => $dnt) {
2021 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
2022 $allRelContactArray[$rel] = array();
2023 // build Query for each relationship
2024 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
2025 NULL, FALSE, FALSE, $queryMode
2027 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
2029 list($id, $direction) = explode('_', $rel, 2);
2030 // identify the relationship direction
2031 $contactA = 'contact_id_a';
2032 $contactB = 'contact_id_b';
2033 if ($direction == 'b_a') {
2034 $contactA = 'contact_id_b';
2035 $contactB = 'contact_id_a';
2037 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
2039 $relationshipJoin = $relationshipClause = '';
2040 if (!$selectAll && $componentTable) {
2041 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
2043 elseif (!empty($relIDs)) {
2044 $relID = implode(',', $relIDs);
2045 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
2048 $relationFrom = " {$relationFrom}
2049 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
2050 {$relationshipJoin} ";
2052 //check for active relationship status only
2053 $today = date('Ymd');
2054 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
2055 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
2056 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
2057 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
2058 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
2060 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
2061 while ($allRelContactDAO->fetch()) {
2062 //FIX Me: Migrate this to table rather than array
2063 // build the array of all related contacts
2064 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
2066 $allRelContactDAO->free();
2069 return array($relationQuery, $allRelContactArray);
2074 * @param $iterationDAO
2075 * @param $fieldValue
2078 * @param $selectedPaymentFields
2079 * @param $paymentDetails
2080 * @param string $paymentTableId
2083 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId) {
2085 if ($field == 'id') {
2086 return $iterationDAO->contact_id
;
2087 // special case for calculated field
2089 elseif ($field == 'source_contact_id') {
2090 return $iterationDAO->contact_id
;
2092 elseif ($field == 'pledge_balance_amount') {
2093 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
2094 // special case for calculated field
2096 elseif ($field == 'pledge_next_pay_amount') {
2097 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
2099 elseif (isset($fieldValue) &&
2102 //check for custom data
2103 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
2104 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2107 elseif (in_array($field, array(
2112 //special case for greeting replacement
2113 $fldValue = "{$field}_display";
2114 return $iterationDAO->$fldValue;
2117 //normal fields with a touch of CRM-3157
2120 case 'world_region':
2121 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
2123 case 'state_province':
2124 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
2127 case 'preferred_communication_method':
2128 case 'preferred_mail_format':
2129 case 'communication_style':
2130 return $i18n->crm_translate($fieldValue);
2133 if (isset($metadata[$field])) {
2134 // No I don't know why we do it this way & whether we could
2135 // make better use of pseudoConstants.
2136 if (!empty($metadata[$field]['context'])) {
2137 return $i18n->crm_translate($fieldValue, $metadata[$field]);
2139 if (!empty($metadata[$field]['pseudoconstant'])) {
2140 // This is not our normal syntax for pseudoconstants but I am a bit loath to
2141 // call an external function until sure it is not increasing php processing given this
2142 // may be iterated 100,000 times & we already have the $imProvider var loaded.
2143 // That can be next refactor...
2144 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
2145 // but I have to reach a stable point....
2146 $varName = $metadata[$field]['pseudoconstant']['var'];
2147 if ($varName === 'imProviders') {
2148 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
2150 if ($varName === 'phoneTypes') {
2151 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
2160 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
2161 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
2162 $payFieldMapper = array(
2163 'componentPaymentField_total_amount' => 'total_amount',
2164 'componentPaymentField_contribution_status' => 'contribution_status',
2165 'componentPaymentField_payment_instrument' => 'pay_instru',
2166 'componentPaymentField_transaction_id' => 'trxn_id',
2167 'componentPaymentField_received_date' => 'receive_date',
2169 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
2172 // if field is empty or null