3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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;
308 $relationField = NULL;
310 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
311 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
312 // without manually testing the export of IM provider still works.
313 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
314 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
324 $queryMode = self
::getQueryMode($exportMode);
327 //construct return properties
328 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
329 $locationTypeFields = array(
331 'supplemental_address_1',
332 'supplemental_address_2',
335 'postal_code_suffix',
345 foreach ($fields as $key => $value) {
346 $phoneTypeId = $imProviderId = NULL;
347 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
351 // get phoneType id and IM service provider id separately
352 if ($fieldName == 'phone') {
353 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
355 elseif ($fieldName == 'im') {
356 $imProviderId = CRM_Utils_Array
::value(3, $value);
359 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
360 if (!empty($value[2])) {
361 $relationField = CRM_Utils_Array
::value(2, $value);
362 if (trim(CRM_Utils_Array
::value(3, $value))) {
363 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
366 $relLocTypeId = 'Primary';
369 if ($relationField == 'phone') {
370 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
372 elseif ($relationField == 'im') {
373 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
376 elseif (!empty($value[4])) {
377 $relationField = CRM_Utils_Array
::value(4, $value);
378 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
379 if ($relationField == 'phone') {
380 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
382 elseif ($relationField == 'im') {
383 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
388 $contactType = CRM_Utils_Array
::value(0, $value);
389 $locTypeId = CRM_Utils_Array
::value(2, $value);
391 if ($relationField) {
392 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
393 if ($relPhoneTypeId) {
394 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
396 elseif ($relIMProviderId) {
397 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
400 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
402 $relPhoneTypeId = $relIMProviderId = NULL;
405 $returnProperties[$relationshipTypes][$relationField] = 1;
408 elseif (is_numeric($locTypeId)) {
410 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
412 elseif ($imProviderId) {
413 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
416 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
420 //hack to fix component fields
421 //revert mix of event_id and title
422 if ($fieldName == 'event_id') {
423 $returnProperties['event_id'] = 1;
426 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
427 array_key_exists($fieldName, self
::componentPaymentFields())
429 $selectedPaymentFields = TRUE;
430 $paymentTableId = 'participant_id';
431 $returnProperties[$fieldName] = 1;
434 $returnProperties[$fieldName] = 1;
438 $defaultExportMode = self
::defaultReturnProperty($exportMode);
439 if ($defaultExportMode) {
440 $returnProperties[$defaultExportMode] = 1;
445 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
446 foreach ($fields as $key => $var) {
447 if ($key && (substr($key, 0, 6) != 'custom')) {
449 $returnProperties[$key] = 1;
454 $returnProperties['location_type'] = 1;
455 $returnProperties['im_provider'] = 1;
456 $returnProperties['phone_type_id'] = 1;
457 $returnProperties['provider_id'] = 1;
458 $returnProperties['current_employer'] = 1;
461 $extraProperties = self
::defineExtraProperties($queryMode);
462 $paymentFields = $extraProperties['paymentFields'];
463 $extraReturnProperties = $extraProperties['extraReturnProperties'];
464 $paymentTableId = $extraProperties['paymentTableId'];
466 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
467 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
468 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
469 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
470 $componentReturnProperties = array_merge(
471 $componentReturnProperties,
472 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
474 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
476 if (!empty($extraReturnProperties)) {
477 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
480 // unset non exportable fields for components
481 $nonExpoFields = array(
485 'contribution_status_id',
487 'pledge_payment_status_id',
489 foreach ($nonExpoFields as $value) {
490 unset($returnProperties[$value]);
495 if ($mergeSameAddress) {
496 //make sure the addressee fields are selected
497 //while using merge same address feature
498 $returnProperties['addressee'] = 1;
499 $returnProperties['postal_greeting'] = 1;
500 $returnProperties['email_greeting'] = 1;
501 $returnProperties['street_name'] = 1;
502 $returnProperties['household_name'] = 1;
503 $returnProperties['street_address'] = 1;
504 $returnProperties['city'] = 1;
505 $returnProperties['state_province'] = 1;
507 // some columns are required for assistance incase they are not already present
508 $exportParams['merge_same_address']['temp_columns'] = array();
509 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
510 foreach ($tempColumns as $column) {
511 if (!array_key_exists($column, $returnProperties)) {
512 $returnProperties[$column] = 1;
513 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
514 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
519 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
520 // If an Additional Group is selected, then all contacts in that group are
521 // added to the export set (filtering out duplicates).
523 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";
524 CRM_Core_DAO
::executeQuery($query);
527 if ($moreReturnProperties) {
529 if (!empty($moreReturnProperties['group'])) {
530 unset($moreReturnProperties['group']);
531 $moreReturnProperties['groups'] = 1;
533 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
536 $exportParams['postal_mailing_export']['temp_columns'] = array();
537 if ($exportParams['exportOption'] == 2 &&
538 isset($exportParams['postal_mailing_export']) &&
539 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
541 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
542 foreach ($postalColumns as $column) {
543 if (!array_key_exists($column, $returnProperties)) {
544 $returnProperties[$column] = 1;
545 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
550 // rectify params to what proximity search expects if there is a value for prox_distance
552 if (!empty($params)) {
553 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
556 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
557 FALSE, FALSE, $queryMode,
558 FALSE, TRUE, TRUE, NULL, $queryOperator
563 $query->_sort
= $order;
564 list($select, $from, $where, $having) = $query->query();
566 if ($mergeSameHousehold == 1) {
567 if (empty($returnProperties['id'])) {
568 $returnProperties['id'] = 1;
571 //also merge Head of Household
572 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
573 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
575 foreach ($returnProperties as $key => $value) {
576 if (!array_key_exists($key, $contactRelationshipTypes)) {
577 $returnProperties[$relationKeyMOH][$key] = $value;
578 $returnProperties[$relationKeyHOH][$key] = $value;
582 unset($returnProperties[$relationKeyMOH]['location_type']);
583 unset($returnProperties[$relationKeyMOH]['im_provider']);
584 unset($returnProperties[$relationKeyHOH]['location_type']);
585 unset($returnProperties[$relationKeyHOH]['im_provider']);
588 $allRelContactArray = $relationQuery = array();
590 foreach ($contactRelationshipTypes as $rel => $dnt) {
591 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
592 $allRelContactArray[$rel] = array();
593 // build Query for each relationship
594 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
595 NULL, FALSE, FALSE, $queryMode
597 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
599 list($id, $direction) = explode('_', $rel, 2);
600 // identify the relationship direction
601 $contactA = 'contact_id_a';
602 $contactB = 'contact_id_b';
603 if ($direction == 'b_a') {
604 $contactA = 'contact_id_b';
605 $contactB = 'contact_id_a';
607 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
610 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
611 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
612 $query = "SELECT contact_id FROM civicrm_activity_contact
613 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
614 record_type_id = {$sourceID}";
615 $dao = CRM_Core_DAO
::executeQuery($query);
616 while ($dao->fetch()) {
617 $relIDs[] = $dao->contact_id
;
621 $component = self
::exportComponent($exportMode);
623 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
624 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
627 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
631 $relationshipJoin = $relationshipClause = '';
632 if (!$selectAll && $componentTable) {
633 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
635 elseif (!empty($relIDs)) {
636 $relID = implode(',', $relIDs);
637 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
640 $relationFrom = " {$relationFrom}
641 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
642 {$relationshipJoin} ";
644 //check for active relationship status only
645 $today = date('Ymd');
646 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
647 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
648 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
649 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
650 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
652 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
653 while ($allRelContactDAO->fetch()) {
654 //FIX Me: Migrate this to table rather than array
655 // build the array of all related contacts
656 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
658 $allRelContactDAO->free();
662 // make sure the groups stuff is included only if specifically specified
663 // by the fields param (CRM-1969), else we limit the contacts outputted to only
664 // ones that are part of a group
665 if (!empty($returnProperties['groups'])) {
666 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
667 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
668 // total hack for export, CRM-3618
669 $from = str_replace($oldClause,
675 if (!$selectAll && $componentTable) {
676 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
678 elseif ($componentClause) {
680 $where = "WHERE $componentClause";
683 $where .= " AND $componentClause";
687 // CRM-13982 - check if is deleted
688 $excludeTrashed = TRUE;
689 foreach ($params as $value) {
690 if ($value[0] == 'contact_is_deleted') {
691 $excludeTrashed = FALSE;
694 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
697 $where = "WHERE $trashClause";
700 $where .= " AND $trashClause";
703 $queryString = "$select $from $where $having";
705 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
707 $queryString .= $groupBy;
710 // always add contact_a.id to the ORDER clause
711 // so the order is deterministic
713 if (strpos('contact_a.id', $order) === FALSE) {
714 $order .= ", contact_a.id";
717 list($field, $dir) = explode(' ', $order, 2);
718 $field = trim($field);
719 if (!empty($returnProperties[$field])) {
721 $queryString .= " ORDER BY $order";
725 $multipleSelectFields = array('preferred_communication_method' => 1);
727 $addPaymentHeader = FALSE;
729 $paymentDetails = array();
730 if ($paymentFields ||
$selectedPaymentFields) {
732 // get payment related in for event and members
733 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
734 //get all payment headers.
735 // If we haven't selected specific payment fields, load in all the
737 if (!$selectedPaymentFields) {
738 $paymentHeaders = self
::componentPaymentFields();
739 if (!empty($paymentDetails)) {
740 $addPaymentHeader = TRUE;
743 // If we have selected specific payment fields, leave the payment headers
744 // as an empty array; the headers for each selected field will be added
747 $paymentHeaders = array();
749 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
752 $componentDetails = array();
755 $rowCount = self
::EXPORT_ROW_COUNT
;
757 // we write to temp table often to avoid using too much memory
762 // for CRM-3157 purposes
763 $i18n = CRM_Core_I18n
::singleton();
765 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
767 $limitReached = FALSE;
768 while (!$limitReached) {
769 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
770 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
771 // If this is less than our limit by the end of the iteration we do not need to run the query again to
772 // check if some remain.
773 $rowsThisIteration = 0;
775 while ($dao->fetch()) {
777 $rowsThisIteration++
;
780 //convert the pseudo constants
781 // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
782 // temporary iterationDAO object to get around it.
783 // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
784 // these additional properties are NOT reset when the $dao cycles through the while loop
785 // nor are they overwritten as they are not in the loop
786 // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
787 // relevant property is set.
788 // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
789 // export class before tackling a better architectural fix
790 $iterationDAO = clone $dao;
791 $query->convertToPseudoNames($iterationDAO);
793 //first loop through output columns so that we return what is required, and in same order.
794 $relationshipField = 0;
795 foreach ($outputColumns as $field => $value) {
797 // add im_provider to $dao object
798 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
799 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
802 //build row values (data)
804 if (property_exists($iterationDAO, $field)) {
805 $fieldValue = $iterationDAO->$field;
806 // to get phone type from phone type id
807 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
808 $fieldValue = $phoneTypes[$fieldValue];
810 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
811 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
813 elseif (strstr($field, 'master_id')) {
814 $masterAddressId = NULL;
815 if (isset($iterationDAO->$field)) {
816 $masterAddressId = $iterationDAO->$field;
818 // get display name of contact that address is shared.
819 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id
);
823 if ($field == 'id') {
824 $row[$field] = $iterationDAO->contact_id
;
825 // special case for calculated field
827 elseif ($field == 'source_contact_id') {
828 $row[$field] = $iterationDAO->contact_id
;
830 elseif ($field == 'pledge_balance_amount') {
831 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
832 // special case for calculated field
834 elseif ($field == 'pledge_next_pay_amount') {
835 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
837 elseif (array_key_exists($field, $contactRelationshipTypes)) {
838 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
839 $relationQuery[$field]->convertToPseudoNames($relDAO);
840 foreach ($value as $relationField => $relationValue) {
841 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
842 $fieldValue = $relDAO->$relationField;
843 if ($relationField == 'phone_type_id') {
844 $fieldValue = $phoneTypes[$relationValue];
846 elseif ($relationField == 'provider_id') {
847 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
850 elseif (is_object($relDAO) && in_array($relationField, array(
856 //special case for greeting replacement
857 $fldValue = "{$relationField}_display";
858 $fieldValue = $relDAO->$fldValue;
861 elseif (is_object($relDAO) && $relationField == 'state_province') {
862 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
864 elseif (is_object($relDAO) && $relationField == 'country') {
865 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
870 $field = $field . '_';
872 if (array_key_exists($relationField, $multipleSelectFields)) {
873 $param = array($relationField => $fieldValue);
874 $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
875 CRM_Core_OptionGroup
::lookupValues($param, $names, FALSE);
876 $fieldValue = $param[$relationField];
878 if (is_object($relDAO) && $relationField == 'id') {
879 $row[$field . $relationField] = $relDAO->contact_id
;
881 elseif (is_array($relationValue) && $relationField == 'location') {
882 foreach ($relationValue as $ltype => $val) {
883 foreach (array_keys($val) as $fld) {
884 $type = explode('-', $fld);
885 $fldValue = "{$ltype}-" . $type[0];
886 if (!empty($type[1])) {
887 $fldValue .= "-" . $type[1];
889 // CRM-3157: localise country, region (both have ‘country’ context)
890 // and state_province (‘province’ context)
892 case (!is_object($relDAO)):
893 $row[$field . '_' . $fldValue] = '';
896 case in_array('country', $type):
897 case in_array('world_region', $type):
898 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
899 array('context' => 'country')
903 case in_array('state_province', $type):
904 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
905 array('context' => 'province')
910 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
916 elseif (isset($fieldValue) && $fieldValue != '') {
917 //check for custom data
918 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
919 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
922 //normal relationship fields
923 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
924 switch ($relationField) {
927 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
930 case 'state_province':
931 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
935 $row[$field . $relationField] = $fieldValue;
941 // if relation field is empty or null
942 $row[$field . $relationField] = '';
946 elseif (isset($fieldValue) &&
949 //check for custom data
950 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
951 $row[$field] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
953 elseif (array_key_exists($field, $multipleSelectFields)) {
955 $paramsNew = array($field => $fieldValue);
956 if ($field == 'test_tutoring') {
957 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
960 elseif (substr($field, 0, 4) == 'cmr_') {
961 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
964 $name = array($field => array('newName' => $field, 'groupName' => $field));
966 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
967 $row[$field] = $paramsNew[$field];
970 elseif (in_array($field, array(
975 //special case for greeting replacement
976 $fldValue = "{$field}_display";
977 $row[$field] = $iterationDAO->$fldValue;
980 //normal fields with a touch of CRM-3157
984 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
987 case 'state_province':
988 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
992 case 'preferred_communication_method':
993 case 'preferred_mail_format':
994 case 'communication_style':
995 $row[$field] = $i18n->crm_translate($fieldValue);
999 if (isset($metadata[$field])) {
1000 // No I don't know why we do it this way & whether we could
1001 // make better use of pseudoConstants.
1002 if (!empty($metadata[$field]['context'])) {
1003 $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
1006 if (!empty($metadata[$field]['pseudoconstant'])) {
1007 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1008 // call an external function until sure it is not increasing php processing given this
1009 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1010 // That can be next refactor...
1011 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1012 // but I have to reach a stable point....
1013 $varName = $metadata[$field]['pseudoconstant']['var'];
1014 $labels = $
$varName;
1015 $row[$field] = $labels[$fieldValue];
1020 $row[$field] = $fieldValue;
1025 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1026 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1027 $payFieldMapper = array(
1028 'componentPaymentField_total_amount' => 'total_amount',
1029 'componentPaymentField_contribution_status' => 'contribution_status',
1030 'componentPaymentField_payment_instrument' => 'pay_instru',
1031 'componentPaymentField_transaction_id' => 'trxn_id',
1032 'componentPaymentField_received_date' => 'receive_date',
1034 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1037 // if field is empty or null
1042 // add payment headers if required
1043 if ($addPaymentHeader && $paymentFields) {
1044 // @todo rather than do this for every single row do it before the loop starts.
1045 // where other header definitions take place.
1046 $headerRows = array_merge($headerRows, $paymentHeaders);
1047 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1048 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1053 $exportTempTable = self
::createTempTable($sqlColumns);
1056 //build header only once
1059 // If specific payment fields have been selected for export, payment
1060 // data will already be in $row. Otherwise, add payment related
1061 // information, if appropriate.
1062 if ($addPaymentHeader) {
1063 if (!$selectedPaymentFields) {
1064 if ($paymentFields) {
1065 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1066 if (!is_array($paymentData) ||
empty($paymentData)) {
1067 $paymentData = $nullContributionDetails;
1069 $row = array_merge($row, $paymentData);
1071 elseif (!empty($paymentDetails)) {
1072 $row = array_merge($row, $nullContributionDetails);
1076 //remove organization name for individuals if it is set for current employer
1077 if (!empty($row['contact_type']) &&
1078 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1080 $row['organization_name'] = '';
1083 // add component info
1084 // write the row to a file
1085 $componentDetails[] = $row;
1087 // output every $tempRowCount rows
1088 if ($count %
$tempRowCount == 0) {
1089 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1090 $componentDetails = array();
1094 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
1095 $limitReached = TRUE;
1097 $offset +
= $rowCount;
1100 if ($exportTempTable) {
1101 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1103 // do merge same address and merge same household processing
1104 if ($mergeSameAddress) {
1105 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1108 // merge the records if they have corresponding households
1109 if ($mergeSameHousehold) {
1110 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1111 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1114 // if postalMailing option is checked, exclude contacts who are deceased, have
1115 // "Do not mail" privacy setting, or have no street address
1116 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1117 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1119 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1123 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1125 // In order to be able to write a unit test against this function we need to suppress
1126 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
1127 if (empty($exportParams['suppress_csv_for_testing'])) {
1128 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1131 // return tableName and sqlColumns in test context
1132 return array($exportTempTable, $sqlColumns);
1135 // delete the export temp table and component table
1136 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1137 CRM_Core_DAO
::executeQuery($sql);
1139 CRM_Utils_System
::civiExit();
1142 CRM_Core_Error
::fatal(ts('No records to export'));
1147 * Name of the export file based on mode.
1149 * @param string $output
1157 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1159 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1160 return ts('CiviCRM Contact Search');
1162 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1163 return ts('CiviCRM Contribution Search');
1165 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1166 return ts('CiviCRM Member Search');
1168 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1169 return ts('CiviCRM Participant Search');
1171 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1172 return ts('CiviCRM Pledge Search');
1174 case CRM_Export_Form_Select
::CASE_EXPORT
:
1175 return ts('CiviCRM Case Search');
1177 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1178 return ts('CiviCRM Grant Search');
1180 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1181 return ts('CiviCRM Activity Search');
1186 * Handle import error file creation.
1188 public static function invoke() {
1189 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
1190 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
1191 if (empty($parserName) ||
empty($type)) {
1195 // clean and ensure parserName is a valid string
1196 $parserName = CRM_Utils_String
::munge($parserName);
1197 $parserClass = explode('_', $parserName);
1199 // make sure parserClass is in the CRM namespace and
1200 // at least 3 levels deep
1201 if ($parserClass[0] == 'CRM' &&
1202 count($parserClass) >= 3
1204 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
1205 // ensure the functions exists
1206 if (method_exists($parserName, 'errorFileName') &&
1207 method_exists($parserName, 'saveFileName')
1209 $errorFileName = $parserName::errorFileName($type);
1210 $saveFileName = $parserName::saveFileName($type);
1211 if (!empty($errorFileName) && !empty($saveFileName)) {
1212 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
1213 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
1214 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
1215 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1216 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1218 readfile($errorFileName);
1222 CRM_Utils_System
::civiExit();
1226 * @param $customSearchClass
1227 * @param $formValues
1230 public static function exportCustom($customSearchClass, $formValues, $order) {
1231 $ext = CRM_Extension_System
::singleton()->getMapper();
1232 if (!$ext->isExtensionClass($customSearchClass)) {
1233 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1236 require_once $ext->classToPath($customSearchClass);
1238 $search = new $customSearchClass($formValues);
1240 $includeContactIDs = FALSE;
1241 if ($formValues['radio_ts'] == 'ts_sel') {
1242 $includeContactIDs = TRUE;
1245 $sql = $search->all(0, 0, $order, $includeContactIDs);
1247 $columns = $search->columns();
1249 $header = array_keys($columns);
1250 $fields = array_values($columns);
1253 $dao = CRM_Core_DAO
::executeQuery($sql);
1255 if (method_exists($search, 'alterRow')) {
1258 while ($dao->fetch()) {
1261 foreach ($fields as $field) {
1262 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
1263 $row[$field] = $dao->$unqualified_field;
1266 $search->alterRow($row);
1271 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1272 CRM_Utils_System
::civiExit();
1277 * @param $sqlColumns
1280 public static function sqlColumnDefn($query, &$sqlColumns, $field) {
1281 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1285 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1286 if ($fieldName == 'id') {
1287 $fieldName = 'civicrm_primary_id';
1290 // early exit for master_id, CRM-12100
1291 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1292 // also for current_employer, CRM-16939
1293 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1294 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1298 if (substr($fieldName, -11) == 'campaign_id') {
1300 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1304 $lookUp = array('prefix_id', 'suffix_id');
1305 // set the sql columns
1306 if (isset($query->_fields
[$field]['type'])) {
1307 switch ($query->_fields
[$field]['type']) {
1308 case CRM_Utils_Type
::T_INT
:
1309 case CRM_Utils_Type
::T_BOOLEAN
:
1310 if (in_array($field, $lookUp)) {
1311 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1314 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1318 case CRM_Utils_Type
::T_STRING
:
1319 if (isset($query->_fields
[$field]['maxlength'])) {
1320 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1323 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1327 case CRM_Utils_Type
::T_TEXT
:
1328 case CRM_Utils_Type
::T_LONGTEXT
:
1329 case CRM_Utils_Type
::T_BLOB
:
1330 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1331 $sqlColumns[$fieldName] = "$fieldName longtext";
1334 case CRM_Utils_Type
::T_FLOAT
:
1335 case CRM_Utils_Type
::T_ENUM
:
1336 case CRM_Utils_Type
::T_DATE
:
1337 case CRM_Utils_Type
::T_TIME
:
1338 case CRM_Utils_Type
::T_TIMESTAMP
:
1339 case CRM_Utils_Type
::T_MONEY
:
1340 case CRM_Utils_Type
::T_EMAIL
:
1341 case CRM_Utils_Type
::T_URL
:
1342 case CRM_Utils_Type
::T_CCNUM
:
1344 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1349 if (substr($fieldName, -3, 3) == '_id') {
1350 // for trxn_id and its variants use a longer buffer
1351 // to accommodate different systems - CRM-13739
1352 static $notRealIDFields = NULL;
1353 if ($notRealIDFields == NULL) {
1354 $notRealIDFields = array('trxn_id', 'componentpaymentfield_transaction_id', 'phone_type_id');
1357 if (in_array($fieldName, $notRealIDFields)) {
1358 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1361 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1364 elseif (substr($fieldName, -5, 5) == '_note') {
1365 $sqlColumns[$fieldName] = "$fieldName text";
1368 $changeFields = array(
1374 if (in_array($fieldName, $changeFields)) {
1375 $sqlColumns[$fieldName] = "$fieldName text";
1378 // set the sql columns for custom data
1379 if (isset($query->_fields
[$field]['data_type'])) {
1381 switch ($query->_fields
[$field]['data_type']) {
1383 // May be option labels, which could be up to 512 characters
1384 $length = max(512, CRM_Utils_Array
::value('text_length', $query->_fields
[$field]));
1385 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1389 case 'StateProvince':
1391 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1395 $sqlColumns[$fieldName] = "$fieldName text";
1399 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1404 $sqlColumns[$fieldName] = "$fieldName text";
1412 * @param string $tableName
1414 * @param $sqlColumns
1416 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1417 if (empty($details)) {
1426 $id = CRM_Core_DAO
::singleValueQuery($sql);
1431 $sqlClause = array();
1433 foreach ($details as $dontCare => $row) {
1435 $valueString = array($id);
1436 foreach ($row as $dontCare => $value) {
1437 if (empty($value)) {
1438 $valueString[] = "''";
1441 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1444 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1447 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1449 $sqlValueString = implode(",\n", $sqlClause);
1452 INSERT INTO $tableName $sqlColumnString
1453 VALUES $sqlValueString
1456 CRM_Core_DAO
::executeQuery($sql);
1460 * @param $sqlColumns
1464 public static function createTempTable(&$sqlColumns) {
1465 //creating a temporary table for the search result that need be exported
1466 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1468 // also create the sql table
1469 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1470 CRM_Core_DAO
::executeQuery($sql);
1473 CREATE TABLE {$exportTempTable} (
1474 id int unsigned NOT NULL AUTO_INCREMENT,
1476 $sql .= implode(",\n", array_values($sqlColumns));
1481 // add indexes for street_address and household_name if present
1482 $addIndices = array(
1485 'civicrm_primary_id',
1488 foreach ($addIndices as $index) {
1489 if (isset($sqlColumns[$index])) {
1491 INDEX index_{$index}( $index )
1497 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1500 CRM_Core_DAO
::executeQuery($sql);
1501 return $exportTempTable;
1505 * @param string $tableName
1506 * @param $headerRows
1507 * @param $sqlColumns
1508 * @param array $exportParams
1510 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1511 // check if any records are present based on if they have used shared address feature,
1512 // and not based on if city / state .. matches.
1514 SELECT r1.id as copy_id,
1515 r1.civicrm_primary_id as copy_contact_id,
1516 r1.addressee as copy_addressee,
1517 r1.addressee_id as copy_addressee_id,
1518 r1.postal_greeting as copy_postal_greeting,
1519 r1.postal_greeting_id as copy_postal_greeting_id,
1521 r2.civicrm_primary_id as master_contact_id,
1522 r2.postal_greeting as master_postal_greeting,
1523 r2.postal_greeting_id as master_postal_greeting_id,
1524 r2.addressee as master_addressee,
1525 r2.addressee_id as master_addressee_id
1527 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1528 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1530 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1532 // find all the records that have the same street address BUT not in a household
1533 // require match on city and state as well
1535 SELECT r1.id as master_id,
1536 r1.civicrm_primary_id as master_contact_id,
1537 r1.postal_greeting as master_postal_greeting,
1538 r1.postal_greeting_id as master_postal_greeting_id,
1539 r1.addressee as master_addressee,
1540 r1.addressee_id as master_addressee_id,
1542 r2.civicrm_primary_id as copy_contact_id,
1543 r2.postal_greeting as copy_postal_greeting,
1544 r2.postal_greeting_id as copy_postal_greeting_id,
1545 r2.addressee as copy_addressee,
1546 r2.addressee_id as copy_addressee_id
1548 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1549 r1.city = r2.city AND
1550 r1.state_province_id = r2.state_province_id )
1551 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1552 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1553 AND ( r1.street_address != '' )
1557 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1559 // unset ids from $merge already present in $linkedMerge
1560 foreach ($linkedMerge as $masterID => $values) {
1561 $keys = array($masterID);
1562 $keys = array_merge($keys, array_keys($values['copy']));
1563 foreach ($merge as $mid => $vals) {
1564 if (in_array($mid, $keys)) {
1565 unset($merge[$mid]);
1568 foreach ($values['copy'] as $copyId) {
1569 if (in_array($copyId, $keys)) {
1570 unset($merge[$mid]['copy'][$copyId]);
1576 $merge = $merge +
$linkedMerge;
1578 foreach ($merge as $masterID => $values) {
1581 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1585 1 => array($values['addressee'], 'String'),
1586 2 => array($values['postalGreeting'], 'String'),
1587 3 => array($values['emailGreeting'], 'String'),
1588 4 => array($masterID, 'Integer'),
1590 CRM_Core_DAO
::executeQuery($sql, $params);
1592 // delete all copies
1593 $deleteIDs = array_keys($values['copy']);
1594 $deleteIDString = implode(',', $deleteIDs);
1596 DELETE FROM $tableName
1597 WHERE id IN ( $deleteIDString )
1599 CRM_Core_DAO
::executeQuery($sql);
1602 // unset temporary columns that were added for postal mailing format
1603 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1604 $unsetKeys = array_keys($sqlColumns);
1605 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1606 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1607 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1614 * @param int $contactId
1615 * @param array $exportParams
1619 public static function _replaceMergeTokens($contactId, $exportParams) {
1620 $greetings = array();
1623 $greetingFields = array(
1627 foreach ($greetingFields as $greeting) {
1628 if (!empty($exportParams[$greeting])) {
1629 $greetingLabel = $exportParams[$greeting];
1630 if (empty($contact)) {
1635 $contact = civicrm_api('contact', 'get', $values);
1637 if (!empty($contact['is_error'])) {
1640 $contact = $contact['values'][$contact['id']];
1643 $tokens = array('contact' => $greetingLabel);
1644 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1651 * The function unsets static part of the string, if token is the dynamic part.
1653 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1654 * i.e 'Hello Alan' => converted to => 'Alan'
1656 * @param string $parsedString
1657 * @param string $defaultGreeting
1658 * @param bool $addressMergeGreetings
1659 * @param string $greetingType
1663 public static function _trimNonTokens(
1664 &$parsedString, $defaultGreeting,
1665 $addressMergeGreetings, $greetingType = 'postal_greeting'
1667 if (!empty($addressMergeGreetings[$greetingType])) {
1668 $greetingLabel = $addressMergeGreetings[$greetingType];
1670 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1672 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1673 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1674 foreach ($stringsToBeReplaced as $key => $string) {
1675 // to keep one space
1676 $stringsToBeReplaced[$key] = ltrim($string);
1678 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1680 return $parsedString;
1685 * @param array $exportParams
1686 * @param bool $sharedAddress
1690 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1691 static $contactGreetingTokens = array();
1693 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1694 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1696 $merge = $parents = array();
1697 $dao = CRM_Core_DAO
::executeQuery($sql);
1699 while ($dao->fetch()) {
1700 $masterID = $dao->master_id
;
1701 $copyID = $dao->copy_id
;
1702 $masterPostalGreeting = $dao->master_postal_greeting
;
1703 $masterAddressee = $dao->master_addressee
;
1704 $copyAddressee = $dao->copy_addressee
;
1706 if (!$sharedAddress) {
1707 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1708 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1710 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1711 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1713 $masterAddressee = CRM_Utils_Array
::value('addressee',
1714 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1717 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1718 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1720 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1721 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1723 $copyAddressee = CRM_Utils_Array
::value('addressee',
1724 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1728 if (!isset($merge[$masterID])) {
1729 // check if this is an intermediate child
1730 // this happens if there are 3 or more matches a,b, c
1731 // the above query will return a, b / a, c / b, c
1732 // we might be doing a bit more work, but for now its ok, unless someone
1733 // knows how to fix the query above
1734 if (isset($parents[$masterID])) {
1735 $masterID = $parents[$masterID];
1738 $merge[$masterID] = array(
1739 'addressee' => $masterAddressee,
1741 'postalGreeting' => $masterPostalGreeting,
1743 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1746 $parents[$copyID] = $masterID;
1748 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1750 if (!empty($exportParams['postal_greeting_other']) &&
1751 count($merge[$masterID]['copy']) >= 1
1753 // use static greetings specified if no of contacts > 2
1754 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1756 elseif ($copyPostalGreeting) {
1757 self
::_trimNonTokens($copyPostalGreeting,
1758 $postalOptions[$dao->copy_postal_greeting_id
],
1761 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1762 // if there happens to be a duplicate, remove it
1763 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1766 if (!empty($exportParams['addressee_other']) &&
1767 count($merge[$masterID]['copy']) >= 1
1769 // use static greetings specified if no of contacts > 2
1770 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1772 elseif ($copyAddressee) {
1773 self
::_trimNonTokens($copyAddressee,
1774 $addresseeOptions[$dao->copy_addressee_id
],
1775 $exportParams, 'addressee'
1777 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1780 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1787 * Merge household record into the individual record
1790 * @param string $exportTempTable
1791 * Temporary temp table that stores the records.
1792 * @param array $headerRows
1793 * Array of headers for the export file.
1794 * @param array $sqlColumns
1795 * Array of names of the table columns of the temp table.
1796 * @param string $prefix
1797 * Name of the relationship type that is prefixed to the table columns.
1799 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1800 $prefixColumn = $prefix . '_';
1801 $allKeys = array_keys($sqlColumns);
1802 $replaced = array();
1803 $headerRows = array_values($headerRows);
1805 // name map of the non standard fields in header rows & sql columns
1806 $mappingFields = array(
1807 'civicrm_primary_id' => 'id',
1808 'contact_source' => 'source',
1809 'current_employer_id' => 'employer_id',
1810 'contact_is_deleted' => 'is_deleted',
1811 'name' => 'address_name',
1812 'provider_id' => 'im_service_provider',
1813 'phone_type_id' => 'phone_type',
1816 //figure out which columns are to be replaced by which ones
1817 foreach ($sqlColumns as $columnNames => $dontCare) {
1818 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1819 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1822 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1824 if (!empty($sqlColumns[$householdColName])) {
1825 $replaced[$columnNames] = $householdColName;
1829 $query = "UPDATE $exportTempTable SET ";
1832 foreach ($replaced as $from => $to) {
1833 $clause[] = "$from = $to ";
1834 unset($sqlColumns[$to]);
1835 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1836 unset($headerRows[$key]);
1839 $query .= implode(",\n", $clause);
1840 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1842 CRM_Core_DAO
::executeQuery($query);
1844 //drop the table columns that store redundant household info
1845 $dropQuery = "ALTER TABLE $exportTempTable ";
1846 foreach ($replaced as $householdColumns) {
1847 $dropClause[] = " DROP $householdColumns ";
1849 $dropQuery .= implode(",\n", $dropClause);
1851 CRM_Core_DAO
::executeQuery($dropQuery);
1853 // also drop the temp table if exists
1854 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1855 CRM_Core_DAO
::executeQuery($sql);
1857 // clean up duplicate records
1859 CREATE TABLE {$exportTempTable}_temp SELECT *
1860 FROM {$exportTempTable}
1861 GROUP BY civicrm_primary_id ";
1863 CRM_Core_DAO
::executeQuery($query);
1865 $query = "DROP TABLE $exportTempTable";
1866 CRM_Core_DAO
::executeQuery($query);
1868 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1869 CRM_Core_DAO
::executeQuery($query);
1873 * @param $exportTempTable
1874 * @param $headerRows
1875 * @param $sqlColumns
1876 * @param $exportMode
1877 * @param null $saveFile
1878 * @param string $batchItems
1880 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1881 $writeHeader = TRUE;
1883 $limit = self
::EXPORT_ROW_COUNT
;
1885 $query = "SELECT * FROM $exportTempTable";
1888 $limitQuery = $query . "
1889 LIMIT $offset, $limit
1891 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1897 $componentDetails = array();
1898 while ($dao->fetch()) {
1901 foreach ($sqlColumns as $column => $dontCare) {
1902 $row[$column] = $dao->$column;
1904 $componentDetails[] = $row;
1906 if ($exportMode == 'financial') {
1907 $getExportFileName = 'CiviCRM Contribution Search';
1910 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1912 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1919 if ($saveFile && !empty($csvRows)) {
1920 $batchItems .= $csvRows;
1923 $writeHeader = FALSE;
1929 * Manipulate header rows for relationship fields.
1931 * @param $headerRows
1932 * @param $contactRelationshipTypes
1934 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1935 foreach ($headerRows as & $header) {
1936 $split = explode('-', $header);
1937 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1938 $split[0] = $relationTypeName;
1939 $header = implode('-', $split);
1945 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1946 * or have no street address
1947 * @param $exportTempTable
1948 * @param $headerRows
1949 * @param $sqlColumns
1950 * @param $exportParams
1952 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1953 $whereClause = array();
1955 if (array_key_exists('is_deceased', $sqlColumns)) {
1956 $whereClause[] = 'is_deceased = 1';
1959 if (array_key_exists('do_not_mail', $sqlColumns)) {
1960 $whereClause[] = 'do_not_mail = 1';
1963 if (array_key_exists('street_address', $sqlColumns)) {
1964 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1966 // check for supplemental_address_1
1967 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1968 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1969 'address_options', TRUE, NULL, TRUE
1971 if (!empty($addressOptions['supplemental_address_1'])) {
1972 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1973 // enclose it again, since we are doing an AND in between a set of ORs
1974 $addressWhereClause = "( $addressWhereClause )";
1978 $whereClause[] = $addressWhereClause;
1981 if (!empty($whereClause)) {
1982 $whereClause = implode(' OR ', $whereClause);
1985 FROM $exportTempTable
1986 WHERE {$whereClause}";
1987 CRM_Core_DAO
::singleValueQuery($query);
1990 // unset temporary columns that were added for postal mailing format
1991 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1992 $unsetKeys = array_keys($sqlColumns);
1993 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1994 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1995 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
2002 * Build componentPayment fields.
2004 public static function componentPaymentFields() {
2005 static $componentPaymentFields;
2006 if (!isset($componentPaymentFields)) {
2007 $componentPaymentFields = array(
2008 'componentPaymentField_total_amount' => ts('Total Amount'),
2009 'componentPaymentField_contribution_status' => ts('Contribution Status'),
2010 'componentPaymentField_received_date' => ts('Date Received'),
2011 'componentPaymentField_payment_instrument' => ts('Payment Method'),
2012 'componentPaymentField_transaction_id' => ts('Transaction ID'),
2015 return $componentPaymentFields;
2019 * Set the definition for the header rows and sql columns based on the field to output.
2021 * @param string $field
2022 * @param array $headerRows
2023 * @param array $sqlColumns
2024 * Columns to go in the temp table.
2025 * @param CRM_Contact_BAO_Query $query
2026 * @param array|string $value
2027 * @param array $phoneTypes
2028 * @param array $imProviders
2029 * @param array $contactRelationshipTypes
2030 * @param string $relationQuery
2031 * @param array $selectedPaymentFields
2034 public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
2036 // Split campaign into 2 fields for id and title
2037 if (substr($field, -14) == 'campaign_title') {
2038 $headerRows[] = ts('Campaign Title');
2040 elseif (substr($field, -11) == 'campaign_id') {
2041 $headerRows[] = ts('Campaign ID');
2043 elseif (isset($query->_fields
[$field]['title'])) {
2044 $headerRows[] = $query->_fields
[$field]['title'];
2046 elseif ($field == 'phone_type_id') {
2047 $headerRows[] = ts('Phone Type');
2049 elseif ($field == 'provider_id') {
2050 $headerRows[] = ts('IM Service Provider');
2052 elseif (substr($field, 0, 5) == 'case_') {
2053 if ($query->_fields
['case'][$field]['title']) {
2054 $headerRows[] = $query->_fields
['case'][$field]['title'];
2056 elseif ($query->_fields
['activity'][$field]['title']) {
2057 $headerRows[] = $query->_fields
['activity'][$field]['title'];
2060 elseif (array_key_exists($field, $contactRelationshipTypes)) {
2061 foreach ($value as $relationField => $relationValue) {
2062 // below block is same as primary block (duplicate)
2063 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
2064 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
2065 $headerName = $field . '-' . $relationField;
2068 if ($relationField == 'current_employer') {
2069 $headerName = $field . '-' . 'current_employer';
2072 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
2076 $headerRows[] = $headerName;
2078 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2080 elseif ($relationField == 'phone_type_id') {
2081 $headerName = $field . '-' . 'Phone Type';
2082 $headerRows[] = $headerName;
2083 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2085 elseif ($relationField == 'provider_id') {
2086 $headerName = $field . '-' . 'Im Service Provider';
2087 $headerRows[] = $headerName;
2088 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2090 elseif ($relationField == 'state_province_id') {
2091 $headerName = $field . '-' . 'state_province_id';
2092 $headerRows[] = $headerName;
2093 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2095 elseif (is_array($relationValue) && $relationField == 'location') {
2096 // fix header for location type case
2097 foreach ($relationValue as $ltype => $val) {
2098 foreach (array_keys($val) as $fld) {
2099 $type = explode('-', $fld);
2101 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
2103 if (!empty($type[1])) {
2104 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
2105 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
2107 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
2108 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
2111 $headerName = $field . '-' . $hdr;
2112 $headerRows[] = $headerName;
2113 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2118 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
2120 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
2121 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
2124 $headerRows[] = $field;
2127 self
::sqlColumnDefn($query, $sqlColumns, $field);
2129 return array($headerRows, $sqlColumns);
2133 * Get the various arrays that we use to structure our output.
2135 * The extraction of these has been moved to a separate function for clarity and so that
2136 * tests can be added - in particular on the $outputHeaders array.
2138 * However it still feels a bit like something that I'm too polite to write down and this should be seen
2139 * as a step on the refactoring path rather than how it should be.
2141 * @param array $returnProperties
2142 * @param CRM_Contact_BAO_Contact $query
2143 * @param array $phoneTypes
2144 * @param array $imProviders
2145 * @param array $contactRelationshipTypes
2146 * @param string $relationQuery
2147 * @param array $selectedPaymentFields
2149 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
2150 * alias for the field generated by BAO_Query object.
2151 * - headerRows Array of the column header strings to put in the csv header - non-associative.
2152 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
2153 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
2154 * I'm too embarassed to discuss here.
2156 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
2157 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
2158 * in the main DAO loop is done once per row & that coule be 100,000 times.)
2159 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
2160 * - a) the function used is more efficient or
2161 * - b) this code is old & outdated. Submit your answers to circular bin or better
2162 * yet find a way to comment them for posterity.
2164 public static function getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
2165 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
2167 foreach ($returnProperties as $key => $value) {
2168 if ($key != 'location' ||
!is_array($value)) {
2169 $outputColumns[$key] = $value;
2170 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2173 foreach ($value as $locationType => $locationFields) {
2174 foreach (array_keys($locationFields) as $locationFieldName) {
2175 $type = explode('-', $locationFieldName);
2177 $actualDBFieldName = $type[0];
2178 $outputFieldName = $locationType . '-' . $query->_fields
[$actualDBFieldName]['title'];
2179 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
2181 if (!empty($type[1])) {
2182 $daoFieldName .= "-" . $type[1];
2183 if ($actualDBFieldName == 'phone') {
2184 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
2186 elseif ($actualDBFieldName == 'im') {
2187 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
2190 if ($type[0] == 'im_provider') {
2191 // Warning: shame inducing hack.
2192 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
2194 self
::sqlColumnDefn($query, $sqlColumns, $outputFieldName);
2195 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2196 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
2197 $metadata[$daoFieldName] = array('context' => 'country');
2199 if ($actualDBFieldName == 'state_province') {
2200 $metadata[$daoFieldName] = array('context' => 'province');
2202 $outputColumns[$daoFieldName] = TRUE;
2207 return array($outputColumns, $headerRows, $sqlColumns, $metadata);