3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
37 * This class contains the functions for Component export
40 class CRM_Export_BAO_Export
{
41 // increase this number a lot to avoid making too many queries
42 // LIMIT is not much faster than a no LIMIT query
44 const EXPORT_ROW_COUNT
= 100000;
47 * Get Querymode based on ExportMode
49 * @param int $exportMode
52 * @return string $Querymode
55 public static function getQueryMode($exportMode) {
56 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
58 switch ($exportMode) {
59 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
60 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
63 case CRM_Export_Form_Select
::EVENT_EXPORT
:
64 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
67 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
68 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
71 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
72 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
75 case CRM_Export_Form_Select
::CASE_EXPORT
:
76 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
79 case CRM_Export_Form_Select
::GRANT_EXPORT
:
80 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
83 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
84 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
91 * Get default return property for export based on mode
93 * @param int $exportMode
96 * @return string $property
97 * Default Return property
99 public static function defaultReturnProperty($exportMode) {
100 // hack to add default return property based on export mode
102 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
103 $property = 'contribution_id';
105 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
106 $property = 'participant_id';
108 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
109 $property = 'membership_id';
111 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
112 $property = 'pledge_id';
114 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
115 $property = 'case_id';
117 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
118 $property = 'grant_id';
120 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
121 $property = 'activity_id';
127 * Get Export component
129 * @param int $exportMode
132 * @return string $component
133 * CiviCRM Export Component
135 public static function exportComponent($exportMode) {
136 switch ($exportMode) {
137 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
138 $component = 'civicrm_contribution';
141 case CRM_Export_Form_Select
::EVENT_EXPORT
:
142 $component = 'civicrm_participant';
145 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
146 $component = 'civicrm_membership';
149 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
150 $component = 'civicrm_pledge';
153 case CRM_Export_Form_Select
::GRANT_EXPORT
:
154 $component = 'civicrm_grant';
161 * Get Query Group By Clause
162 * @param int $exportMode
164 * @param string $queryMode
166 * @param array $returnProperties
168 * @param object $query
169 * CRM_Contact_BAO_Query
171 * @return string $groupBy
174 public static function getGroupBy($exportMode, $queryMode, $returnProperties, $query) {
176 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
177 CRM_Utils_Array
::value('notes', $returnProperties) ||
179 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
181 $groupBy = "contact_a.id";
184 switch ($exportMode) {
185 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
186 $groupBy = 'civicrm_contribution.id';
187 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
188 // especial group by when soft credit columns are included
189 $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
193 case CRM_Export_Form_Select
::EVENT_EXPORT
:
194 $groupBy = 'civicrm_participant.id';
197 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
198 $groupBy = "civicrm_membership.id";
202 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
203 $groupBy = "civicrm_activity.id ";
206 if (!empty($groupBy)) {
207 $groupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($query->_select
, $groupBy);
214 * Define extra properties for the export based on query mode
216 * @param string $queryMode
218 * @return array $extraProperties
221 public static function defineExtraProperties($queryMode) {
222 switch ($queryMode) {
223 case CRM_Contact_BAO_Query
::MODE_EVENT
:
224 $paymentFields = TRUE;
225 $paymentTableId = 'participant_id';
226 $extraReturnProperties = array();
229 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
230 $paymentFields = TRUE;
231 $paymentTableId = 'membership_id';
232 $extraReturnProperties = array();
235 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
236 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
237 $paymentFields = TRUE;
238 $paymentTableId = 'pledge_payment_id';
241 case CRM_Contact_BAO_Query
::MODE_CASE
:
242 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
243 $paymentFields = FALSE;
244 $paymentTableId = '';
248 $paymentFields = FALSE;
249 $paymentTableId = '';
250 $extraReturnProperties = array();
252 $extraProperties = array(
253 'paymentFields' => $paymentFields,
254 'paymentTableId' => $paymentTableId,
255 'extraReturnProperties' => $extraReturnProperties,
257 return $extraProperties;
261 * Get the list the export fields.
263 * @param int $selectAll
264 * User preference while export.
267 * @param array $params
268 * Associated array of fields.
269 * @param string $order
271 * @param array $fields
272 * Associated array of fields.
273 * @param array $moreReturnProperties
274 * Additional return fields.
275 * @param int $exportMode
277 * @param string $componentClause
279 * @param string $componentTable
281 * @param bool $mergeSameAddress
282 * Merge records if they have same address.
283 * @param bool $mergeSameHousehold
284 * Merge records if they belong to the same household.
286 * @param array $exportParams
287 * @param string $queryOperator
290 public static function exportComponents(
296 $moreReturnProperties = NULL,
297 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
298 $componentClause = NULL,
299 $componentTable = NULL,
300 $mergeSameAddress = FALSE,
301 $mergeSameHousehold = FALSE,
302 $exportParams = array(),
303 $queryOperator = 'AND'
306 $returnProperties = array();
307 $paymentFields = $selectedPaymentFields = FALSE;
309 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
310 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
311 // without manually testing the export of IM provider still works.
312 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
313 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
323 $queryMode = self
::getQueryMode($exportMode);
326 //construct return properties
327 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
328 $locationTypeFields = array(
330 'supplemental_address_1',
331 'supplemental_address_2',
334 'postal_code_suffix',
344 foreach ($fields as $key => $value) {
345 $phoneTypeId = $imProviderId = $relationField = NULL;
346 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
350 // get phoneType id and IM service provider id separately
351 if ($fieldName == 'phone') {
352 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
354 elseif ($fieldName == 'im') {
355 $imProviderId = CRM_Utils_Array
::value(3, $value);
358 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
359 if (!empty($value[2])) {
360 $relationField = CRM_Utils_Array
::value(2, $value);
361 if (trim(CRM_Utils_Array
::value(3, $value))) {
362 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
365 $relLocTypeId = 'Primary';
368 if ($relationField == 'phone') {
369 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
371 elseif ($relationField == 'im') {
372 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
375 elseif (!empty($value[4])) {
376 $relationField = CRM_Utils_Array
::value(4, $value);
377 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
378 if ($relationField == 'phone') {
379 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
381 elseif ($relationField == 'im') {
382 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
387 $contactType = CRM_Utils_Array
::value(0, $value);
388 $locTypeId = CRM_Utils_Array
::value(2, $value);
390 if ($relationField) {
391 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
392 if ($relPhoneTypeId) {
393 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
395 elseif ($relIMProviderId) {
396 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
399 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
401 $relPhoneTypeId = $relIMProviderId = NULL;
404 $returnProperties[$relationshipTypes][$relationField] = 1;
407 elseif (is_numeric($locTypeId)) {
409 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
411 elseif ($imProviderId) {
412 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
415 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
419 //hack to fix component fields
420 //revert mix of event_id and title
421 if ($fieldName == 'event_id') {
422 $returnProperties['event_id'] = 1;
425 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
426 array_key_exists($fieldName, self
::componentPaymentFields())
428 $selectedPaymentFields = TRUE;
429 $paymentTableId = 'participant_id';
430 $returnProperties[$fieldName] = 1;
433 $returnProperties[$fieldName] = 1;
437 $defaultExportMode = self
::defaultReturnProperty($exportMode);
438 if ($defaultExportMode) {
439 $returnProperties[$defaultExportMode] = 1;
444 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
445 foreach ($fields as $key => $var) {
446 if ($key && (substr($key, 0, 6) != 'custom')) {
448 $returnProperties[$key] = 1;
453 $returnProperties['location_type'] = 1;
454 $returnProperties['im_provider'] = 1;
455 $returnProperties['phone_type_id'] = 1;
456 $returnProperties['provider_id'] = 1;
457 $returnProperties['current_employer'] = 1;
460 $extraProperties = self
::defineExtraProperties($queryMode);
461 $paymentFields = $extraProperties['paymentFields'];
462 $extraReturnProperties = $extraProperties['extraReturnProperties'];
463 $paymentTableId = $extraProperties['paymentTableId'];
465 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
466 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
467 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
468 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
469 $componentReturnProperties = array_merge(
470 $componentReturnProperties,
471 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
473 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
475 if (!empty($extraReturnProperties)) {
476 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
479 // unset non exportable fields for components
480 $nonExpoFields = array(
484 'contribution_status_id',
486 'pledge_payment_status_id',
488 foreach ($nonExpoFields as $value) {
489 unset($returnProperties[$value]);
494 if ($mergeSameAddress) {
495 //make sure the addressee fields are selected
496 //while using merge same address feature
497 $returnProperties['addressee'] = 1;
498 $returnProperties['postal_greeting'] = 1;
499 $returnProperties['email_greeting'] = 1;
500 $returnProperties['street_name'] = 1;
501 $returnProperties['household_name'] = 1;
502 $returnProperties['street_address'] = 1;
503 $returnProperties['city'] = 1;
504 $returnProperties['state_province'] = 1;
506 // some columns are required for assistance incase they are not already present
507 $exportParams['merge_same_address']['temp_columns'] = array();
508 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
509 foreach ($tempColumns as $column) {
510 if (!array_key_exists($column, $returnProperties)) {
511 $returnProperties[$column] = 1;
512 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
513 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
518 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
519 // If an Additional Group is selected, then all contacts in that group are
520 // added to the export set (filtering out duplicates).
522 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";
523 CRM_Core_DAO
::executeQuery($query);
526 if ($moreReturnProperties) {
528 if (!empty($moreReturnProperties['group'])) {
529 unset($moreReturnProperties['group']);
530 $moreReturnProperties['groups'] = 1;
532 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
535 $exportParams['postal_mailing_export']['temp_columns'] = array();
536 if ($exportParams['exportOption'] == 2 &&
537 isset($exportParams['postal_mailing_export']) &&
538 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
540 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
541 foreach ($postalColumns as $column) {
542 if (!array_key_exists($column, $returnProperties)) {
543 $returnProperties[$column] = 1;
544 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
549 // rectify params to what proximity search expects if there is a value for prox_distance
551 if (!empty($params)) {
552 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
555 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
556 FALSE, FALSE, $queryMode,
557 FALSE, TRUE, TRUE, NULL, $queryOperator
562 $query->_sort
= $order;
563 list($select, $from, $where, $having) = $query->query();
565 if ($mergeSameHousehold == 1) {
566 if (empty($returnProperties['id'])) {
567 $returnProperties['id'] = 1;
570 //also merge Head of Household
571 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
572 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
574 foreach ($returnProperties as $key => $value) {
575 if (!array_key_exists($key, $contactRelationshipTypes)) {
576 $returnProperties[$relationKeyMOH][$key] = $value;
577 $returnProperties[$relationKeyHOH][$key] = $value;
581 unset($returnProperties[$relationKeyMOH]['location_type']);
582 unset($returnProperties[$relationKeyMOH]['im_provider']);
583 unset($returnProperties[$relationKeyHOH]['location_type']);
584 unset($returnProperties[$relationKeyHOH]['im_provider']);
587 $allRelContactArray = $relationQuery = array();
589 foreach ($contactRelationshipTypes as $rel => $dnt) {
590 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
591 $allRelContactArray[$rel] = array();
592 // build Query for each relationship
593 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
594 NULL, FALSE, FALSE, $queryMode
596 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
598 list($id, $direction) = explode('_', $rel, 2);
599 // identify the relationship direction
600 $contactA = 'contact_id_a';
601 $contactB = 'contact_id_b';
602 if ($direction == 'b_a') {
603 $contactA = 'contact_id_b';
604 $contactB = 'contact_id_a';
606 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
609 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
610 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
611 $query = "SELECT contact_id FROM civicrm_activity_contact
612 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
613 record_type_id = {$sourceID}";
614 $dao = CRM_Core_DAO
::executeQuery($query);
615 while ($dao->fetch()) {
616 $relIDs[] = $dao->contact_id
;
620 $component = self
::exportComponent($exportMode);
622 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
623 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
626 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
630 $relationshipJoin = $relationshipClause = '';
631 if (!$selectAll && $componentTable) {
632 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
634 elseif (!empty($relIDs)) {
635 $relID = implode(',', $relIDs);
636 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
639 $relationFrom = " {$relationFrom}
640 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
641 {$relationshipJoin} ";
643 //check for active relationship status only
644 $today = date('Ymd');
645 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
646 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
647 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
648 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
649 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
651 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
652 while ($allRelContactDAO->fetch()) {
653 //FIX Me: Migrate this to table rather than array
654 // build the array of all related contacts
655 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
657 $allRelContactDAO->free();
661 // make sure the groups stuff is included only if specifically specified
662 // by the fields param (CRM-1969), else we limit the contacts outputted to only
663 // ones that are part of a group
664 if (!empty($returnProperties['groups'])) {
665 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
666 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
667 // total hack for export, CRM-3618
668 $from = str_replace($oldClause,
674 if (!$selectAll && $componentTable) {
675 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
677 elseif ($componentClause) {
679 $where = "WHERE $componentClause";
682 $where .= " AND $componentClause";
686 // CRM-13982 - check if is deleted
687 $excludeTrashed = TRUE;
688 foreach ($params as $value) {
689 if ($value[0] == 'contact_is_deleted') {
690 $excludeTrashed = FALSE;
693 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
696 $where = "WHERE $trashClause";
699 $where .= " AND $trashClause";
702 $queryString = "$select $from $where $having";
704 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
706 $queryString .= $groupBy;
709 // always add contact_a.id to the ORDER clause
710 // so the order is deterministic
712 if (strpos('contact_a.id', $order) === FALSE) {
713 $order .= ", contact_a.id";
716 list($field, $dir) = explode(' ', $order, 2);
717 $field = trim($field);
718 if (!empty($returnProperties[$field])) {
720 $queryString .= " ORDER BY $order";
724 $multipleSelectFields = array('preferred_communication_method' => 1);
726 $addPaymentHeader = FALSE;
728 $paymentDetails = array();
729 if ($paymentFields ||
$selectedPaymentFields) {
731 // get payment related in for event and members
732 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
733 //get all payment headers.
734 // If we haven't selected specific payment fields, load in all the
736 if (!$selectedPaymentFields) {
737 $paymentHeaders = self
::componentPaymentFields();
738 if (!empty($paymentDetails)) {
739 $addPaymentHeader = TRUE;
742 // If we have selected specific payment fields, leave the payment headers
743 // as an empty array; the headers for each selected field will be added
746 $paymentHeaders = array();
748 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
751 $componentDetails = array();
754 $rowCount = self
::EXPORT_ROW_COUNT
;
756 // we write to temp table often to avoid using too much memory
761 // for CRM-3157 purposes
762 $i18n = CRM_Core_I18n
::singleton();
764 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
766 $limitReached = FALSE;
767 while (!$limitReached) {
768 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
769 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
770 // If this is less than our limit by the end of the iteration we do not need to run the query again to
771 // check if some remain.
772 $rowsThisIteration = 0;
774 while ($dao->fetch()) {
776 $rowsThisIteration++
;
779 //convert the pseudo constants
780 // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
781 // temporary iterationDAO object to get around it.
782 // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
783 // these additional properties are NOT reset when the $dao cycles through the while loop
784 // nor are they overwritten as they are not in the loop
785 // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
786 // relevant property is set.
787 // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
788 // export class before tackling a better architectural fix
789 $iterationDAO = clone $dao;
790 $query->convertToPseudoNames($iterationDAO);
792 //first loop through output columns so that we return what is required, and in same order.
793 $relationshipField = 0;
794 foreach ($outputColumns as $field => $value) {
796 // add im_provider to $dao object
797 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
798 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
801 //build row values (data)
803 if (property_exists($iterationDAO, $field)) {
804 $fieldValue = $iterationDAO->$field;
805 // to get phone type from phone type id
806 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
807 $fieldValue = $phoneTypes[$fieldValue];
809 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
810 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
812 elseif (strstr($field, 'master_id')) {
813 $masterAddressId = NULL;
814 if (isset($iterationDAO->$field)) {
815 $masterAddressId = $iterationDAO->$field;
817 // get display name of contact that address is shared.
818 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id
);
822 if ($field == 'id') {
823 $row[$field] = $iterationDAO->contact_id
;
824 // special case for calculated field
826 elseif ($field == 'source_contact_id') {
827 $row[$field] = $iterationDAO->contact_id
;
829 elseif ($field == 'pledge_balance_amount') {
830 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
831 // special case for calculated field
833 elseif ($field == 'pledge_next_pay_amount') {
834 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
836 elseif (array_key_exists($field, $contactRelationshipTypes)) {
837 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
838 $relationQuery[$field]->convertToPseudoNames($relDAO);
839 foreach ($value as $relationField => $relationValue) {
840 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
841 $fieldValue = $relDAO->$relationField;
842 if ($relationField == 'phone_type_id') {
843 $fieldValue = $phoneTypes[$relationValue];
845 elseif ($relationField == 'provider_id') {
846 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
849 elseif (is_object($relDAO) && in_array($relationField, array(
855 //special case for greeting replacement
856 $fldValue = "{$relationField}_display";
857 $fieldValue = $relDAO->$fldValue;
860 elseif (is_object($relDAO) && $relationField == 'state_province') {
861 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
863 elseif (is_object($relDAO) && $relationField == 'country') {
864 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
869 $field = $field . '_';
871 if (array_key_exists($relationField, $multipleSelectFields)) {
872 $param = array($relationField => $fieldValue);
873 $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
874 CRM_Core_OptionGroup
::lookupValues($param, $names, FALSE);
875 $fieldValue = $param[$relationField];
877 if (is_object($relDAO) && $relationField == 'id') {
878 $row[$field . $relationField] = $relDAO->contact_id
;
880 elseif (is_array($relationValue) && $relationField == 'location') {
881 foreach ($relationValue as $ltype => $val) {
882 foreach (array_keys($val) as $fld) {
883 $type = explode('-', $fld);
884 $fldValue = "{$ltype}-" . $type[0];
885 if (!empty($type[1])) {
886 $fldValue .= "-" . $type[1];
888 // CRM-3157: localise country, region (both have ‘country’ context)
889 // and state_province (‘province’ context)
891 case (!is_object($relDAO)):
892 $row[$field . '_' . $fldValue] = '';
895 case in_array('country', $type):
896 case in_array('world_region', $type):
897 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
898 array('context' => 'country')
902 case in_array('state_province', $type):
903 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
904 array('context' => 'province')
909 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
915 elseif (isset($fieldValue) && $fieldValue != '') {
916 //check for custom data
917 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
918 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
921 //normal relationship fields
922 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
923 switch ($relationField) {
926 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
929 case 'state_province':
930 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
934 $row[$field . $relationField] = $fieldValue;
940 // if relation field is empty or null
941 $row[$field . $relationField] = '';
945 elseif (isset($fieldValue) &&
948 //check for custom data
949 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
950 $row[$field] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
952 elseif (array_key_exists($field, $multipleSelectFields)) {
954 $paramsNew = array($field => $fieldValue);
955 if ($field == 'test_tutoring') {
956 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
959 elseif (substr($field, 0, 4) == 'cmr_') {
960 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
963 $name = array($field => array('newName' => $field, 'groupName' => $field));
965 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
966 $row[$field] = $paramsNew[$field];
969 elseif (in_array($field, array(
974 //special case for greeting replacement
975 $fldValue = "{$field}_display";
976 $row[$field] = $iterationDAO->$fldValue;
979 //normal fields with a touch of CRM-3157
983 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
986 case 'state_province':
987 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
991 case 'preferred_communication_method':
992 case 'preferred_mail_format':
993 case 'communication_style':
994 $row[$field] = $i18n->crm_translate($fieldValue);
998 if (isset($metadata[$field])) {
999 // No I don't know why we do it this way & whether we could
1000 // make better use of pseudoConstants.
1001 if (!empty($metadata[$field]['context'])) {
1002 $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
1005 if (!empty($metadata[$field]['pseudoconstant'])) {
1006 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1007 // call an external function until sure it is not increasing php processing given this
1008 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1009 // That can be next refactor...
1010 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1011 // but I have to reach a stable point....
1012 $varName = $metadata[$field]['pseudoconstant']['var'];
1013 $labels = $
$varName;
1014 $row[$field] = $labels[$fieldValue];
1019 $row[$field] = $fieldValue;
1024 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1025 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1026 $payFieldMapper = array(
1027 'componentPaymentField_total_amount' => 'total_amount',
1028 'componentPaymentField_contribution_status' => 'contribution_status',
1029 'componentPaymentField_payment_instrument' => 'pay_instru',
1030 'componentPaymentField_transaction_id' => 'trxn_id',
1031 'componentPaymentField_received_date' => 'receive_date',
1033 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1036 // if field is empty or null
1041 // add payment headers if required
1042 if ($addPaymentHeader && $paymentFields) {
1043 // @todo rather than do this for every single row do it before the loop starts.
1044 // where other header definitions take place.
1045 $headerRows = array_merge($headerRows, $paymentHeaders);
1046 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1047 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1052 $exportTempTable = self
::createTempTable($sqlColumns);
1055 //build header only once
1058 // If specific payment fields have been selected for export, payment
1059 // data will already be in $row. Otherwise, add payment related
1060 // information, if appropriate.
1061 if ($addPaymentHeader) {
1062 if (!$selectedPaymentFields) {
1063 if ($paymentFields) {
1064 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1065 if (!is_array($paymentData) ||
empty($paymentData)) {
1066 $paymentData = $nullContributionDetails;
1068 $row = array_merge($row, $paymentData);
1070 elseif (!empty($paymentDetails)) {
1071 $row = array_merge($row, $nullContributionDetails);
1075 //remove organization name for individuals if it is set for current employer
1076 if (!empty($row['contact_type']) &&
1077 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1079 $row['organization_name'] = '';
1082 // add component info
1083 // write the row to a file
1084 $componentDetails[] = $row;
1086 // output every $tempRowCount rows
1087 if ($count %
$tempRowCount == 0) {
1088 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1089 $componentDetails = array();
1093 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
1094 $limitReached = TRUE;
1096 $offset +
= $rowCount;
1099 if ($exportTempTable) {
1100 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1102 // do merge same address and merge same household processing
1103 if ($mergeSameAddress) {
1104 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1107 // merge the records if they have corresponding households
1108 if ($mergeSameHousehold) {
1109 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1110 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1113 // if postalMailing option is checked, exclude contacts who are deceased, have
1114 // "Do not mail" privacy setting, or have no street address
1115 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1116 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1118 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1122 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1124 // In order to be able to write a unit test against this function we need to suppress
1125 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
1126 if (empty($exportParams['suppress_csv_for_testing'])) {
1127 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1130 // return tableName and sqlColumns in test context
1131 return array($exportTempTable, $sqlColumns);
1134 // delete the export temp table and component table
1135 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1136 CRM_Core_DAO
::executeQuery($sql);
1138 CRM_Utils_System
::civiExit();
1141 CRM_Core_Error
::fatal(ts('No records to export'));
1146 * Name of the export file based on mode.
1148 * @param string $output
1156 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1158 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1159 return ts('CiviCRM Contact Search');
1161 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1162 return ts('CiviCRM Contribution Search');
1164 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1165 return ts('CiviCRM Member Search');
1167 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1168 return ts('CiviCRM Participant Search');
1170 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1171 return ts('CiviCRM Pledge Search');
1173 case CRM_Export_Form_Select
::CASE_EXPORT
:
1174 return ts('CiviCRM Case Search');
1176 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1177 return ts('CiviCRM Grant Search');
1179 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1180 return ts('CiviCRM Activity Search');
1185 * Handle import error file creation.
1187 public static function invoke() {
1188 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
1189 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
1190 if (empty($parserName) ||
empty($type)) {
1194 // clean and ensure parserName is a valid string
1195 $parserName = CRM_Utils_String
::munge($parserName);
1196 $parserClass = explode('_', $parserName);
1198 // make sure parserClass is in the CRM namespace and
1199 // at least 3 levels deep
1200 if ($parserClass[0] == 'CRM' &&
1201 count($parserClass) >= 3
1203 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
1204 // ensure the functions exists
1205 if (method_exists($parserName, 'errorFileName') &&
1206 method_exists($parserName, 'saveFileName')
1208 $errorFileName = $parserName::errorFileName($type);
1209 $saveFileName = $parserName::saveFileName($type);
1210 if (!empty($errorFileName) && !empty($saveFileName)) {
1211 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
1212 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
1213 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
1214 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1215 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1217 readfile($errorFileName);
1221 CRM_Utils_System
::civiExit();
1225 * @param $customSearchClass
1226 * @param $formValues
1229 public static function exportCustom($customSearchClass, $formValues, $order) {
1230 $ext = CRM_Extension_System
::singleton()->getMapper();
1231 if (!$ext->isExtensionClass($customSearchClass)) {
1232 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1235 require_once $ext->classToPath($customSearchClass);
1237 $search = new $customSearchClass($formValues);
1239 $includeContactIDs = FALSE;
1240 if ($formValues['radio_ts'] == 'ts_sel') {
1241 $includeContactIDs = TRUE;
1244 $sql = $search->all(0, 0, $order, $includeContactIDs);
1246 $columns = $search->columns();
1248 $header = array_keys($columns);
1249 $fields = array_values($columns);
1252 $dao = CRM_Core_DAO
::executeQuery($sql);
1254 if (method_exists($search, 'alterRow')) {
1257 while ($dao->fetch()) {
1260 foreach ($fields as $field) {
1261 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
1262 $row[$field] = $dao->$unqualified_field;
1265 $search->alterRow($row);
1270 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1271 CRM_Utils_System
::civiExit();
1276 * @param $sqlColumns
1279 public static function sqlColumnDefn($query, &$sqlColumns, $field) {
1280 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1284 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1285 if ($fieldName == 'id') {
1286 $fieldName = 'civicrm_primary_id';
1289 // early exit for master_id, CRM-12100
1290 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1291 // also for current_employer, CRM-16939
1292 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1293 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1297 if (substr($fieldName, -11) == 'campaign_id') {
1299 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1303 $lookUp = array('prefix_id', 'suffix_id');
1304 // set the sql columns
1305 if (isset($query->_fields
[$field]['type'])) {
1306 switch ($query->_fields
[$field]['type']) {
1307 case CRM_Utils_Type
::T_INT
:
1308 case CRM_Utils_Type
::T_BOOLEAN
:
1309 if (in_array($field, $lookUp)) {
1310 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1313 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1317 case CRM_Utils_Type
::T_STRING
:
1318 if (isset($query->_fields
[$field]['maxlength'])) {
1319 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1322 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1326 case CRM_Utils_Type
::T_TEXT
:
1327 case CRM_Utils_Type
::T_LONGTEXT
:
1328 case CRM_Utils_Type
::T_BLOB
:
1329 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1330 $sqlColumns[$fieldName] = "$fieldName longtext";
1333 case CRM_Utils_Type
::T_FLOAT
:
1334 case CRM_Utils_Type
::T_ENUM
:
1335 case CRM_Utils_Type
::T_DATE
:
1336 case CRM_Utils_Type
::T_TIME
:
1337 case CRM_Utils_Type
::T_TIMESTAMP
:
1338 case CRM_Utils_Type
::T_MONEY
:
1339 case CRM_Utils_Type
::T_EMAIL
:
1340 case CRM_Utils_Type
::T_URL
:
1341 case CRM_Utils_Type
::T_CCNUM
:
1343 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1348 if (substr($fieldName, -3, 3) == '_id') {
1349 // for trxn_id and its variants use a longer buffer
1350 // to accommodate different systems - CRM-13739
1351 static $notRealIDFields = NULL;
1352 if ($notRealIDFields == NULL) {
1353 $notRealIDFields = array('trxn_id', 'componentpaymentfield_transaction_id', 'phone_type_id');
1356 if (in_array($fieldName, $notRealIDFields)) {
1357 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1360 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1363 elseif (substr($fieldName, -5, 5) == '_note') {
1364 $sqlColumns[$fieldName] = "$fieldName text";
1367 $changeFields = array(
1373 if (in_array($fieldName, $changeFields)) {
1374 $sqlColumns[$fieldName] = "$fieldName text";
1377 // set the sql columns for custom data
1378 if (isset($query->_fields
[$field]['data_type'])) {
1380 switch ($query->_fields
[$field]['data_type']) {
1382 // May be option labels, which could be up to 512 characters
1383 $length = max(512, CRM_Utils_Array
::value('text_length', $query->_fields
[$field]));
1384 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1388 case 'StateProvince':
1390 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1394 $sqlColumns[$fieldName] = "$fieldName text";
1398 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1403 $sqlColumns[$fieldName] = "$fieldName text";
1411 * @param string $tableName
1413 * @param $sqlColumns
1415 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1416 if (empty($details)) {
1425 $id = CRM_Core_DAO
::singleValueQuery($sql);
1430 $sqlClause = array();
1432 foreach ($details as $dontCare => $row) {
1434 $valueString = array($id);
1435 foreach ($row as $dontCare => $value) {
1436 if (empty($value)) {
1437 $valueString[] = "''";
1440 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1443 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1446 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1448 $sqlValueString = implode(",\n", $sqlClause);
1451 INSERT INTO $tableName $sqlColumnString
1452 VALUES $sqlValueString
1455 CRM_Core_DAO
::executeQuery($sql);
1459 * @param $sqlColumns
1463 public static function createTempTable(&$sqlColumns) {
1464 //creating a temporary table for the search result that need be exported
1465 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1467 // also create the sql table
1468 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1469 CRM_Core_DAO
::executeQuery($sql);
1472 CREATE TABLE {$exportTempTable} (
1473 id int unsigned NOT NULL AUTO_INCREMENT,
1475 $sql .= implode(",\n", array_values($sqlColumns));
1480 // add indexes for street_address and household_name if present
1481 $addIndices = array(
1484 'civicrm_primary_id',
1487 foreach ($addIndices as $index) {
1488 if (isset($sqlColumns[$index])) {
1490 INDEX index_{$index}( $index )
1496 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1499 CRM_Core_DAO
::executeQuery($sql);
1500 return $exportTempTable;
1504 * @param string $tableName
1505 * @param $headerRows
1506 * @param $sqlColumns
1507 * @param array $exportParams
1509 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1510 // check if any records are present based on if they have used shared address feature,
1511 // and not based on if city / state .. matches.
1513 SELECT r1.id as copy_id,
1514 r1.civicrm_primary_id as copy_contact_id,
1515 r1.addressee as copy_addressee,
1516 r1.addressee_id as copy_addressee_id,
1517 r1.postal_greeting as copy_postal_greeting,
1518 r1.postal_greeting_id as copy_postal_greeting_id,
1520 r2.civicrm_primary_id as master_contact_id,
1521 r2.postal_greeting as master_postal_greeting,
1522 r2.postal_greeting_id as master_postal_greeting_id,
1523 r2.addressee as master_addressee,
1524 r2.addressee_id as master_addressee_id
1526 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1527 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1529 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1531 // find all the records that have the same street address BUT not in a household
1532 // require match on city and state as well
1534 SELECT r1.id as master_id,
1535 r1.civicrm_primary_id as master_contact_id,
1536 r1.postal_greeting as master_postal_greeting,
1537 r1.postal_greeting_id as master_postal_greeting_id,
1538 r1.addressee as master_addressee,
1539 r1.addressee_id as master_addressee_id,
1541 r2.civicrm_primary_id as copy_contact_id,
1542 r2.postal_greeting as copy_postal_greeting,
1543 r2.postal_greeting_id as copy_postal_greeting_id,
1544 r2.addressee as copy_addressee,
1545 r2.addressee_id as copy_addressee_id
1547 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1548 r1.city = r2.city AND
1549 r1.state_province_id = r2.state_province_id )
1550 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1551 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1552 AND ( r1.street_address != '' )
1556 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1558 // unset ids from $merge already present in $linkedMerge
1559 foreach ($linkedMerge as $masterID => $values) {
1560 $keys = array($masterID);
1561 $keys = array_merge($keys, array_keys($values['copy']));
1562 foreach ($merge as $mid => $vals) {
1563 if (in_array($mid, $keys)) {
1564 unset($merge[$mid]);
1567 foreach ($values['copy'] as $copyId) {
1568 if (in_array($copyId, $keys)) {
1569 unset($merge[$mid]['copy'][$copyId]);
1575 $merge = $merge +
$linkedMerge;
1577 foreach ($merge as $masterID => $values) {
1580 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1584 1 => array($values['addressee'], 'String'),
1585 2 => array($values['postalGreeting'], 'String'),
1586 3 => array($values['emailGreeting'], 'String'),
1587 4 => array($masterID, 'Integer'),
1589 CRM_Core_DAO
::executeQuery($sql, $params);
1591 // delete all copies
1592 $deleteIDs = array_keys($values['copy']);
1593 $deleteIDString = implode(',', $deleteIDs);
1595 DELETE FROM $tableName
1596 WHERE id IN ( $deleteIDString )
1598 CRM_Core_DAO
::executeQuery($sql);
1601 // unset temporary columns that were added for postal mailing format
1602 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1603 $unsetKeys = array_keys($sqlColumns);
1604 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1605 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1606 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1613 * @param int $contactId
1614 * @param array $exportParams
1618 public static function _replaceMergeTokens($contactId, $exportParams) {
1619 $greetings = array();
1622 $greetingFields = array(
1626 foreach ($greetingFields as $greeting) {
1627 if (!empty($exportParams[$greeting])) {
1628 $greetingLabel = $exportParams[$greeting];
1629 if (empty($contact)) {
1634 $contact = civicrm_api('contact', 'get', $values);
1636 if (!empty($contact['is_error'])) {
1639 $contact = $contact['values'][$contact['id']];
1642 $tokens = array('contact' => $greetingLabel);
1643 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1650 * The function unsets static part of the string, if token is the dynamic part.
1652 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1653 * i.e 'Hello Alan' => converted to => 'Alan'
1655 * @param string $parsedString
1656 * @param string $defaultGreeting
1657 * @param bool $addressMergeGreetings
1658 * @param string $greetingType
1662 public static function _trimNonTokens(
1663 &$parsedString, $defaultGreeting,
1664 $addressMergeGreetings, $greetingType = 'postal_greeting'
1666 if (!empty($addressMergeGreetings[$greetingType])) {
1667 $greetingLabel = $addressMergeGreetings[$greetingType];
1669 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1671 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1672 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1673 foreach ($stringsToBeReplaced as $key => $string) {
1674 // to keep one space
1675 $stringsToBeReplaced[$key] = ltrim($string);
1677 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1679 return $parsedString;
1684 * @param array $exportParams
1685 * @param bool $sharedAddress
1689 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1690 static $contactGreetingTokens = array();
1692 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1693 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1695 $merge = $parents = array();
1696 $dao = CRM_Core_DAO
::executeQuery($sql);
1698 while ($dao->fetch()) {
1699 $masterID = $dao->master_id
;
1700 $copyID = $dao->copy_id
;
1701 $masterPostalGreeting = $dao->master_postal_greeting
;
1702 $masterAddressee = $dao->master_addressee
;
1703 $copyAddressee = $dao->copy_addressee
;
1705 if (!$sharedAddress) {
1706 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1707 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1709 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1710 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1712 $masterAddressee = CRM_Utils_Array
::value('addressee',
1713 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1716 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1717 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1719 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1720 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1722 $copyAddressee = CRM_Utils_Array
::value('addressee',
1723 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1727 if (!isset($merge[$masterID])) {
1728 // check if this is an intermediate child
1729 // this happens if there are 3 or more matches a,b, c
1730 // the above query will return a, b / a, c / b, c
1731 // we might be doing a bit more work, but for now its ok, unless someone
1732 // knows how to fix the query above
1733 if (isset($parents[$masterID])) {
1734 $masterID = $parents[$masterID];
1737 $merge[$masterID] = array(
1738 'addressee' => $masterAddressee,
1740 'postalGreeting' => $masterPostalGreeting,
1742 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1745 $parents[$copyID] = $masterID;
1747 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1749 if (!empty($exportParams['postal_greeting_other']) &&
1750 count($merge[$masterID]['copy']) >= 1
1752 // use static greetings specified if no of contacts > 2
1753 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1755 elseif ($copyPostalGreeting) {
1756 self
::_trimNonTokens($copyPostalGreeting,
1757 $postalOptions[$dao->copy_postal_greeting_id
],
1760 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1761 // if there happens to be a duplicate, remove it
1762 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1765 if (!empty($exportParams['addressee_other']) &&
1766 count($merge[$masterID]['copy']) >= 1
1768 // use static greetings specified if no of contacts > 2
1769 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1771 elseif ($copyAddressee) {
1772 self
::_trimNonTokens($copyAddressee,
1773 $addresseeOptions[$dao->copy_addressee_id
],
1774 $exportParams, 'addressee'
1776 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1779 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1786 * Merge household record into the individual record
1789 * @param string $exportTempTable
1790 * Temporary temp table that stores the records.
1791 * @param array $headerRows
1792 * Array of headers for the export file.
1793 * @param array $sqlColumns
1794 * Array of names of the table columns of the temp table.
1795 * @param string $prefix
1796 * Name of the relationship type that is prefixed to the table columns.
1798 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1799 $prefixColumn = $prefix . '_';
1800 $allKeys = array_keys($sqlColumns);
1801 $replaced = array();
1802 $headerRows = array_values($headerRows);
1804 // name map of the non standard fields in header rows & sql columns
1805 $mappingFields = array(
1806 'civicrm_primary_id' => 'id',
1807 'contact_source' => 'source',
1808 'current_employer_id' => 'employer_id',
1809 'contact_is_deleted' => 'is_deleted',
1810 'name' => 'address_name',
1811 'provider_id' => 'im_service_provider',
1812 'phone_type_id' => 'phone_type',
1815 //figure out which columns are to be replaced by which ones
1816 foreach ($sqlColumns as $columnNames => $dontCare) {
1817 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1818 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1821 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1823 if (!empty($sqlColumns[$householdColName])) {
1824 $replaced[$columnNames] = $householdColName;
1828 $query = "UPDATE $exportTempTable SET ";
1831 foreach ($replaced as $from => $to) {
1832 $clause[] = "$from = $to ";
1833 unset($sqlColumns[$to]);
1834 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1835 unset($headerRows[$key]);
1838 $query .= implode(",\n", $clause);
1839 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1841 CRM_Core_DAO
::executeQuery($query);
1843 //drop the table columns that store redundant household info
1844 $dropQuery = "ALTER TABLE $exportTempTable ";
1845 foreach ($replaced as $householdColumns) {
1846 $dropClause[] = " DROP $householdColumns ";
1848 $dropQuery .= implode(",\n", $dropClause);
1850 CRM_Core_DAO
::executeQuery($dropQuery);
1852 // also drop the temp table if exists
1853 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1854 CRM_Core_DAO
::executeQuery($sql);
1856 // clean up duplicate records
1858 CREATE TABLE {$exportTempTable}_temp SELECT *
1859 FROM {$exportTempTable}
1860 GROUP BY civicrm_primary_id ";
1862 CRM_Core_DAO
::executeQuery($query);
1864 $query = "DROP TABLE $exportTempTable";
1865 CRM_Core_DAO
::executeQuery($query);
1867 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1868 CRM_Core_DAO
::executeQuery($query);
1872 * @param $exportTempTable
1873 * @param $headerRows
1874 * @param $sqlColumns
1875 * @param $exportMode
1876 * @param null $saveFile
1877 * @param string $batchItems
1879 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1880 $writeHeader = TRUE;
1882 $limit = self
::EXPORT_ROW_COUNT
;
1884 $query = "SELECT * FROM $exportTempTable";
1887 $limitQuery = $query . "
1888 LIMIT $offset, $limit
1890 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1896 $componentDetails = array();
1897 while ($dao->fetch()) {
1900 foreach ($sqlColumns as $column => $dontCare) {
1901 $row[$column] = $dao->$column;
1903 $componentDetails[] = $row;
1905 if ($exportMode == 'financial') {
1906 $getExportFileName = 'CiviCRM Contribution Search';
1909 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1911 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1918 if ($saveFile && !empty($csvRows)) {
1919 $batchItems .= $csvRows;
1922 $writeHeader = FALSE;
1928 * Manipulate header rows for relationship fields.
1930 * @param $headerRows
1931 * @param $contactRelationshipTypes
1933 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1934 foreach ($headerRows as & $header) {
1935 $split = explode('-', $header);
1936 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1937 $split[0] = $relationTypeName;
1938 $header = implode('-', $split);
1944 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1945 * or have no street address
1946 * @param $exportTempTable
1947 * @param $headerRows
1948 * @param $sqlColumns
1949 * @param $exportParams
1951 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1952 $whereClause = array();
1954 if (array_key_exists('is_deceased', $sqlColumns)) {
1955 $whereClause[] = 'is_deceased = 1';
1958 if (array_key_exists('do_not_mail', $sqlColumns)) {
1959 $whereClause[] = 'do_not_mail = 1';
1962 if (array_key_exists('street_address', $sqlColumns)) {
1963 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1965 // check for supplemental_address_1
1966 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1967 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1968 'address_options', TRUE, NULL, TRUE
1970 if (!empty($addressOptions['supplemental_address_1'])) {
1971 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1972 // enclose it again, since we are doing an AND in between a set of ORs
1973 $addressWhereClause = "( $addressWhereClause )";
1977 $whereClause[] = $addressWhereClause;
1980 if (!empty($whereClause)) {
1981 $whereClause = implode(' OR ', $whereClause);
1984 FROM $exportTempTable
1985 WHERE {$whereClause}";
1986 CRM_Core_DAO
::singleValueQuery($query);
1989 // unset temporary columns that were added for postal mailing format
1990 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1991 $unsetKeys = array_keys($sqlColumns);
1992 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1993 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1994 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
2001 * Build componentPayment fields.
2003 public static function componentPaymentFields() {
2004 static $componentPaymentFields;
2005 if (!isset($componentPaymentFields)) {
2006 $componentPaymentFields = array(
2007 'componentPaymentField_total_amount' => ts('Total Amount'),
2008 'componentPaymentField_contribution_status' => ts('Contribution Status'),
2009 'componentPaymentField_received_date' => ts('Date Received'),
2010 'componentPaymentField_payment_instrument' => ts('Payment Method'),
2011 'componentPaymentField_transaction_id' => ts('Transaction ID'),
2014 return $componentPaymentFields;
2018 * Set the definition for the header rows and sql columns based on the field to output.
2020 * @param string $field
2021 * @param array $headerRows
2022 * @param array $sqlColumns
2023 * Columns to go in the temp table.
2024 * @param CRM_Contact_BAO_Query $query
2025 * @param array|string $value
2026 * @param array $phoneTypes
2027 * @param array $imProviders
2028 * @param array $contactRelationshipTypes
2029 * @param string $relationQuery
2030 * @param array $selectedPaymentFields
2033 public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
2035 // Split campaign into 2 fields for id and title
2036 if (substr($field, -14) == 'campaign_title') {
2037 $headerRows[] = ts('Campaign Title');
2039 elseif (substr($field, -11) == 'campaign_id') {
2040 $headerRows[] = ts('Campaign ID');
2042 elseif (isset($query->_fields
[$field]['title'])) {
2043 $headerRows[] = $query->_fields
[$field]['title'];
2045 elseif ($field == 'phone_type_id') {
2046 $headerRows[] = ts('Phone Type');
2048 elseif ($field == 'provider_id') {
2049 $headerRows[] = ts('IM Service Provider');
2051 elseif (substr($field, 0, 5) == 'case_') {
2052 if ($query->_fields
['case'][$field]['title']) {
2053 $headerRows[] = $query->_fields
['case'][$field]['title'];
2055 elseif ($query->_fields
['activity'][$field]['title']) {
2056 $headerRows[] = $query->_fields
['activity'][$field]['title'];
2059 elseif (array_key_exists($field, $contactRelationshipTypes)) {
2060 foreach ($value as $relationField => $relationValue) {
2061 // below block is same as primary block (duplicate)
2062 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
2063 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
2064 $headerName = $field . '-' . $relationField;
2067 if ($relationField == 'current_employer') {
2068 $headerName = $field . '-' . 'current_employer';
2071 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
2075 $headerRows[] = $headerName;
2077 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2079 elseif ($relationField == 'phone_type_id') {
2080 $headerName = $field . '-' . 'Phone Type';
2081 $headerRows[] = $headerName;
2082 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2084 elseif ($relationField == 'provider_id') {
2085 $headerName = $field . '-' . 'Im Service Provider';
2086 $headerRows[] = $headerName;
2087 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2089 elseif ($relationField == 'state_province_id') {
2090 $headerName = $field . '-' . 'state_province_id';
2091 $headerRows[] = $headerName;
2092 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2094 elseif (is_array($relationValue) && $relationField == 'location') {
2095 // fix header for location type case
2096 foreach ($relationValue as $ltype => $val) {
2097 foreach (array_keys($val) as $fld) {
2098 $type = explode('-', $fld);
2100 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
2102 if (!empty($type[1])) {
2103 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
2104 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
2106 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
2107 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
2110 $headerName = $field . '-' . $hdr;
2111 $headerRows[] = $headerName;
2112 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2117 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
2119 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
2120 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
2123 $headerRows[] = $field;
2126 self
::sqlColumnDefn($query, $sqlColumns, $field);
2128 return array($headerRows, $sqlColumns);
2132 * Get the various arrays that we use to structure our output.
2134 * The extraction of these has been moved to a separate function for clarity and so that
2135 * tests can be added - in particular on the $outputHeaders array.
2137 * However it still feels a bit like something that I'm too polite to write down and this should be seen
2138 * as a step on the refactoring path rather than how it should be.
2140 * @param array $returnProperties
2141 * @param CRM_Contact_BAO_Contact $query
2142 * @param array $phoneTypes
2143 * @param array $imProviders
2144 * @param array $contactRelationshipTypes
2145 * @param string $relationQuery
2146 * @param array $selectedPaymentFields
2148 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
2149 * alias for the field generated by BAO_Query object.
2150 * - headerRows Array of the column header strings to put in the csv header - non-associative.
2151 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
2152 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
2153 * I'm too embarassed to discuss here.
2155 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
2156 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
2157 * in the main DAO loop is done once per row & that coule be 100,000 times.)
2158 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
2159 * - a) the function used is more efficient or
2160 * - b) this code is old & outdated. Submit your answers to circular bin or better
2161 * yet find a way to comment them for posterity.
2163 public static function getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
2164 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
2166 foreach ($returnProperties as $key => $value) {
2167 if ($key != 'location' ||
!is_array($value)) {
2168 $outputColumns[$key] = $value;
2169 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2172 foreach ($value as $locationType => $locationFields) {
2173 foreach (array_keys($locationFields) as $locationFieldName) {
2174 $type = explode('-', $locationFieldName);
2176 $actualDBFieldName = $type[0];
2177 $outputFieldName = $locationType . '-' . $query->_fields
[$actualDBFieldName]['title'];
2178 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
2180 if (!empty($type[1])) {
2181 $daoFieldName .= "-" . $type[1];
2182 if ($actualDBFieldName == 'phone') {
2183 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
2185 elseif ($actualDBFieldName == 'im') {
2186 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
2189 if ($type[0] == 'im_provider') {
2190 // Warning: shame inducing hack.
2191 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
2193 self
::sqlColumnDefn($query, $sqlColumns, $outputFieldName);
2194 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2195 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
2196 $metadata[$daoFieldName] = array('context' => 'country');
2198 if ($actualDBFieldName == 'state_province') {
2199 $metadata[$daoFieldName] = array('context' => 'province');
2201 $outputColumns[$daoFieldName] = TRUE;
2206 return array($outputColumns, $headerRows, $sqlColumns, $metadata);