3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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
= 10000;
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
101 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
102 $property = 'contribution_id';
104 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
105 $property = 'participant_id';
107 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
108 $property = 'membership_id';
110 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
111 $property = 'pledge_id';
113 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
114 $property = 'case_id';
116 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
117 $property = 'grant_id';
119 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
120 $property = 'activity_id';
122 elseif ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
123 $property = 'contact_id';
129 * Get Export component
131 * @param int $exportMode
134 * @return string $component
135 * CiviCRM Export Component
137 public static function exportComponent($exportMode) {
138 switch ($exportMode) {
139 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
140 $component = 'civicrm_contribution';
143 case CRM_Export_Form_Select
::EVENT_EXPORT
:
144 $component = 'civicrm_participant';
147 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
148 $component = 'civicrm_membership';
151 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
152 $component = 'civicrm_pledge';
155 case CRM_Export_Form_Select
::GRANT_EXPORT
:
156 $component = 'civicrm_grant';
163 * Get Query Group By Clause
164 * @param int $exportMode
166 * @param string $queryMode
168 * @param array $returnProperties
170 * @param object $query
171 * CRM_Contact_BAO_Query
173 * @return string $groupBy
176 public static function getGroupBy($exportMode, $queryMode, $returnProperties, $query) {
177 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
178 CRM_Utils_Array
::value('notes', $returnProperties) ||
180 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
182 $groupBy = " GROUP BY contact_a.id";
185 switch ($exportMode) {
186 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
187 $groupBy = 'GROUP BY civicrm_contribution.id';
188 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
189 // especial group by when soft credit columns are included
190 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
194 case CRM_Export_Form_Select
::EVENT_EXPORT
:
195 $groupBy = 'GROUP BY civicrm_participant.id';
198 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
199 $groupBy = " GROUP BY civicrm_membership.id";
203 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
204 $groupBy = " GROUP BY civicrm_activity.id ";
207 $groupBy = !empty($groupBy) ?
$groupBy : '';
213 * Define extra properties for the export based on query mode
215 * @param string $queryMode
217 * @return array $extraProperties
220 public static function defineExtraProperties($queryMode) {
221 switch ($queryMode) {
222 case CRM_Contact_BAO_Query
::MODE_EVENT
:
223 $paymentFields = TRUE;
224 $paymentTableId = 'participant_id';
225 $extraReturnProperties = array();
228 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
229 $paymentFields = TRUE;
230 $paymentTableId = 'membership_id';
231 $extraReturnProperties = array();
234 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
235 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
236 $paymentFields = TRUE;
237 $paymentTableId = 'pledge_payment_id';
240 case CRM_Contact_BAO_Query
::MODE_CASE
:
241 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
242 $paymentFields = FALSE;
243 $paymentTableId = '';
247 $paymentFields = FALSE;
248 $paymentTableId = '';
249 $extraReturnProperties = array();
251 $extraProperties = array(
252 'paymentFields' => $paymentFields,
253 'paymentTableId' => $paymentTableId,
254 'extraReturnProperties' => $extraReturnProperties,
256 return $extraProperties;
260 * Get the list the export fields.
262 * @param int $selectAll
263 * User preference while export.
266 * @param array $params
267 * Associated array of fields.
268 * @param string $order
270 * @param array $fields
271 * Associated array of fields.
272 * @param array $moreReturnProperties
273 * Additional return fields.
274 * @param int $exportMode
276 * @param string $componentClause
278 * @param string $componentTable
280 * @param bool $mergeSameAddress
281 * Merge records if they have same address.
282 * @param bool $mergeSameHousehold
283 * Merge records if they belong to the same household.
285 * @param array $exportParams
286 * @param string $queryOperator
289 public static function exportComponents(
295 $moreReturnProperties = NULL,
296 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
297 $componentClause = NULL,
298 $componentTable = NULL,
299 $mergeSameAddress = FALSE,
300 $mergeSameHousehold = FALSE,
301 $exportParams = array(),
302 $queryOperator = 'AND'
305 $returnProperties = array();
306 $paymentFields = $selectedPaymentFields = FALSE;
307 $relationField = NULL;
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 = 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 $returnProperties[self
::defaultReturnProperty($exportMode)] = 1;
441 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
442 foreach ($fields as $key => $var) {
443 if ($key && (substr($key, 0, 6) != 'custom')) {
445 $returnProperties[$key] = 1;
450 $returnProperties['location_type'] = 1;
451 $returnProperties['im_provider'] = 1;
452 $returnProperties['phone_type_id'] = 1;
453 $returnProperties['provider_id'] = 1;
454 $returnProperties['current_employer'] = 1;
457 $extraProperties = self
::defineExtraProperties($queryMode);
458 $paymentFields = $extraProperties['paymentFields'];
459 $extraReturnProperties = $extraProperties['extraReturnProperties'];
460 $paymentTableId = $extraProperties['paymentTableId'];
462 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
463 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
464 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
465 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
466 $componentReturnProperties = array_merge(
467 $componentReturnProperties,
468 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
470 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
472 if (!empty($extraReturnProperties)) {
473 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
476 // unset non exportable fields for components
477 $nonExpoFields = array(
481 'contribution_status_id',
483 'pledge_payment_status_id',
485 foreach ($nonExpoFields as $value) {
486 unset($returnProperties[$value]);
491 if ($mergeSameAddress) {
492 //make sure the addressee fields are selected
493 //while using merge same address feature
494 $returnProperties['addressee'] = 1;
495 $returnProperties['postal_greeting'] = 1;
496 $returnProperties['email_greeting'] = 1;
497 $returnProperties['street_name'] = 1;
498 $returnProperties['household_name'] = 1;
499 $returnProperties['street_address'] = 1;
500 $returnProperties['city'] = 1;
501 $returnProperties['state_province'] = 1;
503 // some columns are required for assistance incase they are not already present
504 $exportParams['merge_same_address']['temp_columns'] = array();
505 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
506 foreach ($tempColumns as $column) {
507 if (!array_key_exists($column, $returnProperties)) {
508 $returnProperties[$column] = 1;
509 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
510 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
515 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
516 // If an Additional Group is selected, then all contacts in that group are
517 // added to the export set (filtering out duplicates).
519 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";
520 CRM_Core_DAO
::executeQuery($query);
523 if ($moreReturnProperties) {
525 if (!empty($moreReturnProperties['group'])) {
526 unset($moreReturnProperties['group']);
527 $moreReturnProperties['groups'] = 1;
529 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
532 $exportParams['postal_mailing_export']['temp_columns'] = array();
533 if ($exportParams['exportOption'] == 2 &&
534 isset($exportParams['postal_mailing_export']) &&
535 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
537 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
538 foreach ($postalColumns as $column) {
539 if (!array_key_exists($column, $returnProperties)) {
540 $returnProperties[$column] = 1;
541 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
546 // rectify params to what proximity search expects if there is a value for prox_distance
548 if (!empty($params)) {
549 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
552 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
553 FALSE, FALSE, $queryMode,
554 FALSE, TRUE, TRUE, NULL, $queryOperator
559 $query->_sort
= $order;
560 list($select, $from, $where, $having) = $query->query();
562 if ($mergeSameHousehold == 1) {
563 if (!$returnProperties['id']) {
564 $returnProperties['id'] = 1;
567 //also merge Head of Household
568 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
569 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
571 foreach ($returnProperties as $key => $value) {
572 if (!array_key_exists($key, $contactRelationshipTypes)) {
573 $returnProperties[$relationKeyMOH][$key] = $value;
574 $returnProperties[$relationKeyHOH][$key] = $value;
578 unset($returnProperties[$relationKeyMOH]['location_type']);
579 unset($returnProperties[$relationKeyMOH]['im_provider']);
580 unset($returnProperties[$relationKeyHOH]['location_type']);
581 unset($returnProperties[$relationKeyHOH]['im_provider']);
584 $allRelContactArray = $relationQuery = array();
586 foreach ($contactRelationshipTypes as $rel => $dnt) {
587 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
588 $allRelContactArray[$rel] = array();
589 // build Query for each relationship
590 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
591 NULL, FALSE, FALSE, $queryMode
593 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
595 list($id, $direction) = explode('_', $rel, 2);
596 // identify the relationship direction
597 $contactA = 'contact_id_a';
598 $contactB = 'contact_id_b';
599 if ($direction == 'b_a') {
600 $contactA = 'contact_id_b';
601 $contactB = 'contact_id_a';
603 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
606 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
607 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
608 $query = "SELECT contact_id FROM civicrm_activity_contact
609 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
610 record_type_id = {$sourceID}";
611 $dao = CRM_Core_DAO
::executeQuery($query);
612 while ($dao->fetch()) {
613 $relIDs[] = $dao->contact_id
;
617 $component = self
::exportComponent($exportMode);
619 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
620 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
623 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
627 $relationshipJoin = $relationshipClause = '';
628 if (!$selectAll && $componentTable) {
629 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
631 elseif (!empty($relIDs)) {
632 $relID = implode(',', $relIDs);
633 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
636 $relationFrom = " {$relationFrom}
637 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
638 {$relationshipJoin} ";
640 //check for active relationship status only
641 $today = date('Ymd');
642 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
643 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
644 $relationGroupBy = " GROUP BY crel.{$contactA}";
645 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
646 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
648 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
649 while ($allRelContactDAO->fetch()) {
650 //FIX Me: Migrate this to table rather than array
651 // build the array of all related contacts
652 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
654 $allRelContactDAO->free();
658 // make sure the groups stuff is included only if specifically specified
659 // by the fields param (CRM-1969), else we limit the contacts outputted to only
660 // ones that are part of a group
661 if (!empty($returnProperties['groups'])) {
662 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
663 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
664 // total hack for export, CRM-3618
665 $from = str_replace($oldClause,
671 if (!$selectAll && $componentTable) {
672 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
674 elseif ($componentClause) {
676 $where = "WHERE $componentClause";
679 $where .= " AND $componentClause";
683 // CRM-13982 - check if is deleted
684 $excludeTrashed = TRUE;
685 foreach ($params as $value) {
686 if ($value[0] == 'contact_is_deleted') {
687 $excludeTrashed = FALSE;
690 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
693 $where = "WHERE $trashClause";
696 $where .= " AND $trashClause";
699 $queryString = "$select $from $where $having";
701 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
703 $queryString .= $groupBy;
705 // always add contact_a.id to the ORDER clause
706 // so the order is deterministic
708 if (strpos('contact_a.id', $order) === FALSE) {
709 $order .= ", contact_a.id";
713 list($field, $dir) = explode(' ', $order, 2);
714 $field = trim($field);
715 if (!empty($returnProperties[$field])) {
717 $queryString .= " ORDER BY $order";
721 $multipleSelectFields = array('preferred_communication_method' => 1);
723 $addPaymentHeader = FALSE;
725 $paymentDetails = array();
726 if ($paymentFields ||
$selectedPaymentFields) {
728 // get payment related in for event and members
729 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
730 //get all payment headers.
731 // If we haven't selected specific payment fields, load in all the
733 if (!$selectedPaymentFields) {
734 $paymentHeaders = self
::componentPaymentFields();
735 if (!empty($paymentDetails)) {
736 $addPaymentHeader = TRUE;
739 // If we have selected specific payment fields, leave the payment headers
740 // as an empty array; the headers for each selected field will be added
743 $paymentHeaders = array();
745 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
748 $componentDetails = array();
751 $rowCount = self
::EXPORT_ROW_COUNT
;
753 // we write to temp table often to avoid using too much memory
758 // for CRM-3157 purposes
759 $i18n = CRM_Core_I18n
::singleton();
760 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
763 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
764 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
769 while ($dao->fetch()) {
773 //convert the pseudo constants
774 // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
775 // temporary iterationDAO object to get around it.
776 // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
777 // these additional properties are NOT reset when the $dao cycles through the while loop
778 // nor are they overwritten as they are not in the loop
779 // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
780 // relevant property is set.
781 // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
782 // export class before tackling a better architectural fix
783 $iterationDAO = clone $dao;
784 $query->convertToPseudoNames($iterationDAO);
786 //first loop through output columns so that we return what is required, and in same order.
787 $relationshipField = 0;
788 foreach ($outputColumns as $field => $value) {
790 // add im_provider to $dao object
791 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
792 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
795 //build row values (data)
797 if (property_exists($iterationDAO, $field)) {
798 $fieldValue = $iterationDAO->$field;
799 // to get phone type from phone type id
800 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
801 $fieldValue = $phoneTypes[$fieldValue];
803 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
804 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
806 elseif ($field == 'master_id') {
807 $masterAddressId = NULL;
808 if (isset($iterationDAO->master_id
)) {
809 $masterAddressId = $iterationDAO->master_id
;
811 // get display name of contact that address is shared.
812 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id
);
816 if ($field == 'id') {
817 $row[$field] = $iterationDAO->contact_id
;
818 // special case for calculated field
820 elseif ($field == 'source_contact_id') {
821 $row[$field] = $iterationDAO->contact_id
;
823 elseif ($field == 'pledge_balance_amount') {
824 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
825 // special case for calculated field
827 elseif ($field == 'pledge_next_pay_amount') {
828 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
830 elseif (array_key_exists($field, $contactRelationshipTypes)) {
831 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
832 $relationQuery[$field]->convertToPseudoNames($relDAO);
833 foreach ($value as $relationField => $relationValue) {
834 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
835 $fieldValue = $relDAO->$relationField;
836 if ($relationField == 'phone_type_id') {
837 $fieldValue = $phoneTypes[$relationValue];
839 elseif ($relationField == 'provider_id') {
840 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
843 elseif (is_object($relDAO) && in_array($relationField, array(
849 //special case for greeting replacement
850 $fldValue = "{$relationField}_display";
851 $fieldValue = $relDAO->$fldValue;
854 elseif (is_object($relDAO) && $relationField == 'state_province') {
855 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
857 elseif (is_object($relDAO) && $relationField == 'country') {
858 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
863 $field = $field . '_';
865 if (array_key_exists($relationField, $multipleSelectFields)) {
866 $param = array($relationField => $fieldValue);
867 $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
868 CRM_Core_OptionGroup
::lookupValues($param, $names, FALSE);
869 $fieldValue = $param[$relationField];
871 if (is_object($relDAO) && $relationField == 'id') {
872 $row[$field . $relationField] = $relDAO->contact_id
;
874 elseif (is_array($relationValue) && $relationField == 'location') {
875 foreach ($relationValue as $ltype => $val) {
876 foreach (array_keys($val) as $fld) {
877 $type = explode('-', $fld);
878 $fldValue = "{$ltype}-" . $type[0];
879 if (!empty($type[1])) {
880 $fldValue .= "-" . $type[1];
882 // CRM-3157: localise country, region (both have ‘country’ context)
883 // and state_province (‘province’ context)
885 case (!is_object($relDAO)):
886 $row[$field . '_' . $fldValue] = '';
889 case in_array('country', $type):
890 case in_array('world_region', $type):
891 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
892 array('context' => 'country')
896 case in_array('state_province', $type):
897 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
898 array('context' => 'province')
903 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
909 elseif (isset($fieldValue) && $fieldValue != '') {
910 //check for custom data
911 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
912 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
915 //normal relationship fields
916 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
917 switch ($relationField) {
920 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
923 case 'state_province':
924 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
928 $row[$field . $relationField] = $fieldValue;
934 // if relation field is empty or null
935 $row[$field . $relationField] = '';
939 elseif (isset($fieldValue) &&
942 //check for custom data
943 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
944 $row[$field] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
946 elseif (array_key_exists($field, $multipleSelectFields)) {
948 $paramsNew = array($field => $fieldValue);
949 if ($field == 'test_tutoring') {
950 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
953 elseif (substr($field, 0, 4) == 'cmr_') {
954 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
957 $name = array($field => array('newName' => $field, 'groupName' => $field));
959 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
960 $row[$field] = $paramsNew[$field];
963 elseif (in_array($field, array(
968 //special case for greeting replacement
969 $fldValue = "{$field}_display";
970 $row[$field] = $iterationDAO->$fldValue;
973 //normal fields with a touch of CRM-3157
977 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
980 case 'state_province':
981 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
985 case 'preferred_communication_method':
986 case 'preferred_mail_format':
987 case 'communication_style':
988 $row[$field] = $i18n->crm_translate($fieldValue);
992 if (isset($metadata[$field])) {
993 // No I don't know why we do it this way & whether we could
994 // make better use of pseudoConstants.
995 if (!empty($metadata[$field]['context'])) {
996 $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
999 if (!empty($metadata[$field]['pseudoconstant'])) {
1000 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1001 // call an external function until sure it is not increasing php processing given this
1002 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1003 // That can be next refactor...
1004 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1005 // but I have to reach a stable point....
1006 $varName = $metadata[$field]['pseudoconstant']['var'];
1007 $labels = $
$varName;
1008 $row[$field] = $labels[$fieldValue];
1013 $row[$field] = $fieldValue;
1018 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1019 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1020 $payFieldMapper = array(
1021 'componentPaymentField_total_amount' => 'total_amount',
1022 'componentPaymentField_contribution_status' => 'contribution_status',
1023 'componentPaymentField_payment_instrument' => 'pay_instru',
1024 'componentPaymentField_transaction_id' => 'trxn_id',
1025 'componentPaymentField_received_date' => 'receive_date',
1027 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1030 // if field is empty or null
1035 // add payment headers if required
1036 if ($addPaymentHeader && $paymentFields) {
1037 // @todo rather than do this for every single row do it before the loop starts.
1038 // where other header definitions take place.
1039 $headerRows = array_merge($headerRows, $paymentHeaders);
1040 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1041 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1046 $exportTempTable = self
::createTempTable($sqlColumns);
1049 //build header only once
1052 // If specific payment fields have been selected for export, payment
1053 // data will already be in $row. Otherwise, add payment related
1054 // information, if appropriate.
1055 if ($addPaymentHeader) {
1056 if (!$selectedPaymentFields) {
1057 if ($paymentFields) {
1058 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1059 if (!is_array($paymentData) ||
empty($paymentData)) {
1060 $paymentData = $nullContributionDetails;
1062 $row = array_merge($row, $paymentData);
1064 elseif (!empty($paymentDetails)) {
1065 $row = array_merge($row, $nullContributionDetails);
1069 //remove organization name for individuals if it is set for current employer
1070 if (!empty($row['contact_type']) &&
1071 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1073 $row['organization_name'] = '';
1076 // add component info
1077 // write the row to a file
1078 $componentDetails[] = $row;
1080 // output every $tempRowCount rows
1081 if ($count %
$tempRowCount == 0) {
1082 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1083 $componentDetails = array();
1087 $offset +
= $rowCount;
1090 if ($exportTempTable) {
1091 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1093 // do merge same address and merge same household processing
1094 if ($mergeSameAddress) {
1095 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1098 // merge the records if they have corresponding households
1099 if ($mergeSameHousehold) {
1100 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1101 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1104 // if postalMailing option is checked, exclude contacts who are deceased, have
1105 // "Do not mail" privacy setting, or have no street address
1106 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1107 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1109 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1113 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1115 // In order to be able to write a unit test against this function we need to suppress
1116 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
1117 if (empty($exportParams['suppress_csv_for_testing'])) {
1118 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1121 // delete the export temp table and component table
1122 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1123 CRM_Core_DAO
::executeQuery($sql);
1124 // Do not exit in test context.
1125 if (empty($exportParams['suppress_csv_for_testing'])) {
1126 CRM_Utils_System
::civiExit();
1130 CRM_Core_Error
::fatal(ts('No records to export'));
1135 * Name of the export file based on mode.
1137 * @param string $output
1145 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1147 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1148 return ts('CiviCRM Contact Search');
1150 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1151 return ts('CiviCRM Contribution Search');
1153 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1154 return ts('CiviCRM Member Search');
1156 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1157 return ts('CiviCRM Participant Search');
1159 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1160 return ts('CiviCRM Pledge Search');
1162 case CRM_Export_Form_Select
::CASE_EXPORT
:
1163 return ts('CiviCRM Case Search');
1165 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1166 return ts('CiviCRM Grant Search');
1168 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1169 return ts('CiviCRM Activity Search');
1174 * Handle import error file creation.
1176 public static function invoke() {
1177 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1178 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1179 if (empty($parserName) ||
empty($type)) {
1183 // clean and ensure parserName is a valid string
1184 $parserName = CRM_Utils_String
::munge($parserName);
1185 $parserClass = explode('_', $parserName);
1187 // make sure parserClass is in the CRM namespace and
1188 // at least 3 levels deep
1189 if ($parserClass[0] == 'CRM' &&
1190 count($parserClass) >= 3
1192 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
1193 // ensure the functions exists
1194 if (method_exists($parserName, 'errorFileName') &&
1195 method_exists($parserName, 'saveFileName')
1197 $errorFileName = $parserName::errorFileName($type);
1198 $saveFileName = $parserName::saveFileName($type);
1199 if (!empty($errorFileName) && !empty($saveFileName)) {
1200 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
1201 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
1202 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
1203 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1204 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1206 readfile($errorFileName);
1210 CRM_Utils_System
::civiExit();
1214 * @param $customSearchClass
1215 * @param $formValues
1218 public static function exportCustom($customSearchClass, $formValues, $order) {
1219 $ext = CRM_Extension_System
::singleton()->getMapper();
1220 if (!$ext->isExtensionClass($customSearchClass)) {
1221 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1224 require_once $ext->classToPath($customSearchClass);
1226 $search = new $customSearchClass($formValues);
1228 $includeContactIDs = FALSE;
1229 if ($formValues['radio_ts'] == 'ts_sel') {
1230 $includeContactIDs = TRUE;
1233 $sql = $search->all(0, 0, $order, $includeContactIDs);
1235 $columns = $search->columns();
1237 $header = array_keys($columns);
1238 $fields = array_values($columns);
1241 $dao = CRM_Core_DAO
::executeQuery($sql);
1243 if (method_exists($search, 'alterRow')) {
1246 while ($dao->fetch()) {
1249 foreach ($fields as $field) {
1250 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
1251 $row[$field] = $dao->$unqualified_field;
1254 $search->alterRow($row);
1259 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1260 CRM_Utils_System
::civiExit();
1265 * @param $sqlColumns
1268 public static function sqlColumnDefn($query, &$sqlColumns, $field) {
1269 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1273 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1274 if ($fieldName == 'id') {
1275 $fieldName = 'civicrm_primary_id';
1278 // early exit for master_id, CRM-12100
1279 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1280 // also for current_employer, CRM-16939
1281 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1282 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1286 if (substr($fieldName, -11) == 'campaign_id') {
1288 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1292 $lookUp = array('prefix_id', 'suffix_id');
1293 // set the sql columns
1294 if (isset($query->_fields
[$field]['type'])) {
1295 switch ($query->_fields
[$field]['type']) {
1296 case CRM_Utils_Type
::T_INT
:
1297 case CRM_Utils_Type
::T_BOOLEAN
:
1298 if (in_array($field, $lookUp)) {
1299 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1302 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1306 case CRM_Utils_Type
::T_STRING
:
1307 if (isset($query->_fields
[$field]['maxlength'])) {
1308 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1311 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1315 case CRM_Utils_Type
::T_TEXT
:
1316 case CRM_Utils_Type
::T_LONGTEXT
:
1317 case CRM_Utils_Type
::T_BLOB
:
1318 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1319 $sqlColumns[$fieldName] = "$fieldName longtext";
1322 case CRM_Utils_Type
::T_FLOAT
:
1323 case CRM_Utils_Type
::T_ENUM
:
1324 case CRM_Utils_Type
::T_DATE
:
1325 case CRM_Utils_Type
::T_TIME
:
1326 case CRM_Utils_Type
::T_TIMESTAMP
:
1327 case CRM_Utils_Type
::T_MONEY
:
1328 case CRM_Utils_Type
::T_EMAIL
:
1329 case CRM_Utils_Type
::T_URL
:
1330 case CRM_Utils_Type
::T_CCNUM
:
1332 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1337 if (substr($fieldName, -3, 3) == '_id') {
1338 // for trxn_id and its variants use a longer buffer
1339 // to accommodate different systems - CRM-13739
1340 static $notRealIDFields = NULL;
1341 if ($notRealIDFields == NULL) {
1342 $notRealIDFields = array('trxn_id', 'componentpaymentfield_transaction_id');
1345 if (in_array($fieldName, $notRealIDFields)) {
1346 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1349 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1352 elseif (substr($fieldName, -5, 5) == '_note') {
1353 $sqlColumns[$fieldName] = "$fieldName text";
1356 $changeFields = array(
1362 if (in_array($fieldName, $changeFields)) {
1363 $sqlColumns[$fieldName] = "$fieldName text";
1366 // set the sql columns for custom data
1367 if (isset($query->_fields
[$field]['data_type'])) {
1369 switch ($query->_fields
[$field]['data_type']) {
1371 $length = empty($query->_fields
[$field]['text_length']) ?
255 : $query->_fields
[$field]['text_length'];
1372 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1376 case 'StateProvince':
1378 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1382 $sqlColumns[$fieldName] = "$fieldName text";
1386 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1391 $sqlColumns[$fieldName] = "$fieldName text";
1399 * @param string $tableName
1401 * @param $sqlColumns
1403 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1404 if (empty($details)) {
1413 $id = CRM_Core_DAO
::singleValueQuery($sql);
1418 $sqlClause = array();
1420 foreach ($details as $dontCare => $row) {
1422 $valueString = array($id);
1423 foreach ($row as $dontCare => $value) {
1424 if (empty($value)) {
1425 $valueString[] = "''";
1428 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1431 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1434 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1436 $sqlValueString = implode(",\n", $sqlClause);
1439 INSERT INTO $tableName $sqlColumnString
1440 VALUES $sqlValueString
1443 CRM_Core_DAO
::executeQuery($sql);
1447 * @param $sqlColumns
1451 public static function createTempTable(&$sqlColumns) {
1452 //creating a temporary table for the search result that need be exported
1453 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1455 // also create the sql table
1456 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1457 CRM_Core_DAO
::executeQuery($sql);
1460 CREATE TABLE {$exportTempTable} (
1461 id int unsigned NOT NULL AUTO_INCREMENT,
1463 $sql .= implode(",\n", array_values($sqlColumns));
1468 // add indexes for street_address and household_name if present
1469 $addIndices = array(
1472 'civicrm_primary_id',
1475 foreach ($addIndices as $index) {
1476 if (isset($sqlColumns[$index])) {
1478 INDEX index_{$index}( $index )
1484 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1487 CRM_Core_DAO
::executeQuery($sql);
1488 return $exportTempTable;
1492 * @param string $tableName
1493 * @param $headerRows
1494 * @param $sqlColumns
1495 * @param array $exportParams
1497 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1498 // check if any records are present based on if they have used shared address feature,
1499 // and not based on if city / state .. matches.
1501 SELECT r1.id as copy_id,
1502 r1.civicrm_primary_id as copy_contact_id,
1503 r1.addressee as copy_addressee,
1504 r1.addressee_id as copy_addressee_id,
1505 r1.postal_greeting as copy_postal_greeting,
1506 r1.postal_greeting_id as copy_postal_greeting_id,
1508 r2.civicrm_primary_id as master_contact_id,
1509 r2.postal_greeting as master_postal_greeting,
1510 r2.postal_greeting_id as master_postal_greeting_id,
1511 r2.addressee as master_addressee,
1512 r2.addressee_id as master_addressee_id
1514 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1515 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1517 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1519 // find all the records that have the same street address BUT not in a household
1520 // require match on city and state as well
1522 SELECT r1.id as master_id,
1523 r1.civicrm_primary_id as master_contact_id,
1524 r1.postal_greeting as master_postal_greeting,
1525 r1.postal_greeting_id as master_postal_greeting_id,
1526 r1.addressee as master_addressee,
1527 r1.addressee_id as master_addressee_id,
1529 r2.civicrm_primary_id as copy_contact_id,
1530 r2.postal_greeting as copy_postal_greeting,
1531 r2.postal_greeting_id as copy_postal_greeting_id,
1532 r2.addressee as copy_addressee,
1533 r2.addressee_id as copy_addressee_id
1535 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1536 r1.city = r2.city AND
1537 r1.state_province_id = r2.state_province_id )
1538 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1539 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1540 AND ( r1.street_address != '' )
1544 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1546 // unset ids from $merge already present in $linkedMerge
1547 foreach ($linkedMerge as $masterID => $values) {
1548 $keys = array($masterID);
1549 $keys = array_merge($keys, array_keys($values['copy']));
1550 foreach ($merge as $mid => $vals) {
1551 if (in_array($mid, $keys)) {
1552 unset($merge[$mid]);
1555 foreach ($values['copy'] as $copyId) {
1556 if (in_array($copyId, $keys)) {
1557 unset($merge[$mid]['copy'][$copyId]);
1563 $merge = $merge +
$linkedMerge;
1565 foreach ($merge as $masterID => $values) {
1568 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1572 1 => array($values['addressee'], 'String'),
1573 2 => array($values['postalGreeting'], 'String'),
1574 3 => array($values['emailGreeting'], 'String'),
1575 4 => array($masterID, 'Integer'),
1577 CRM_Core_DAO
::executeQuery($sql, $params);
1579 // delete all copies
1580 $deleteIDs = array_keys($values['copy']);
1581 $deleteIDString = implode(',', $deleteIDs);
1583 DELETE FROM $tableName
1584 WHERE id IN ( $deleteIDString )
1586 CRM_Core_DAO
::executeQuery($sql);
1589 // unset temporary columns that were added for postal mailing format
1590 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1591 $unsetKeys = array_keys($sqlColumns);
1592 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1593 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1594 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1601 * @param int $contactId
1602 * @param array $exportParams
1606 public static function _replaceMergeTokens($contactId, $exportParams) {
1607 $greetings = array();
1610 $greetingFields = array(
1614 foreach ($greetingFields as $greeting) {
1615 if (!empty($exportParams[$greeting])) {
1616 $greetingLabel = $exportParams[$greeting];
1617 if (empty($contact)) {
1622 $contact = civicrm_api('contact', 'get', $values);
1624 if (!empty($contact['is_error'])) {
1627 $contact = $contact['values'][$contact['id']];
1630 $tokens = array('contact' => $greetingLabel);
1631 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1638 * The function unsets static part of the string, if token is the dynamic part.
1640 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1641 * i.e 'Hello Alan' => converted to => 'Alan'
1643 * @param string $parsedString
1644 * @param string $defaultGreeting
1645 * @param bool $addressMergeGreetings
1646 * @param string $greetingType
1650 public static function _trimNonTokens(
1651 &$parsedString, $defaultGreeting,
1652 $addressMergeGreetings, $greetingType = 'postal_greeting'
1654 if (!empty($addressMergeGreetings[$greetingType])) {
1655 $greetingLabel = $addressMergeGreetings[$greetingType];
1657 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1659 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1660 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1661 foreach ($stringsToBeReplaced as $key => $string) {
1662 // to keep one space
1663 $stringsToBeReplaced[$key] = ltrim($string);
1665 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1667 return $parsedString;
1672 * @param array $exportParams
1673 * @param bool $sharedAddress
1677 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1678 static $contactGreetingTokens = array();
1680 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1681 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1683 $merge = $parents = array();
1684 $dao = CRM_Core_DAO
::executeQuery($sql);
1686 while ($dao->fetch()) {
1687 $masterID = $dao->master_id
;
1688 $copyID = $dao->copy_id
;
1689 $masterPostalGreeting = $dao->master_postal_greeting
;
1690 $masterAddressee = $dao->master_addressee
;
1691 $copyAddressee = $dao->copy_addressee
;
1693 if (!$sharedAddress) {
1694 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1695 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1697 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1698 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1700 $masterAddressee = CRM_Utils_Array
::value('addressee',
1701 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1704 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1705 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1707 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1708 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1710 $copyAddressee = CRM_Utils_Array
::value('addressee',
1711 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1715 if (!isset($merge[$masterID])) {
1716 // check if this is an intermediate child
1717 // this happens if there are 3 or more matches a,b, c
1718 // the above query will return a, b / a, c / b, c
1719 // we might be doing a bit more work, but for now its ok, unless someone
1720 // knows how to fix the query above
1721 if (isset($parents[$masterID])) {
1722 $masterID = $parents[$masterID];
1725 $merge[$masterID] = array(
1726 'addressee' => $masterAddressee,
1728 'postalGreeting' => $masterPostalGreeting,
1730 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1733 $parents[$copyID] = $masterID;
1735 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1737 if (!empty($exportParams['postal_greeting_other']) &&
1738 count($merge[$masterID]['copy']) >= 1
1740 // use static greetings specified if no of contacts > 2
1741 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1743 elseif ($copyPostalGreeting) {
1744 self
::_trimNonTokens($copyPostalGreeting,
1745 $postalOptions[$dao->copy_postal_greeting_id
],
1748 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1749 // if there happens to be a duplicate, remove it
1750 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1753 if (!empty($exportParams['addressee_other']) &&
1754 count($merge[$masterID]['copy']) >= 1
1756 // use static greetings specified if no of contacts > 2
1757 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1759 elseif ($copyAddressee) {
1760 self
::_trimNonTokens($copyAddressee,
1761 $addresseeOptions[$dao->copy_addressee_id
],
1762 $exportParams, 'addressee'
1764 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1767 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1774 * Merge household record into the individual record
1777 * @param string $exportTempTable
1778 * Temporary temp table that stores the records.
1779 * @param array $headerRows
1780 * Array of headers for the export file.
1781 * @param array $sqlColumns
1782 * Array of names of the table columns of the temp table.
1783 * @param string $prefix
1784 * Name of the relationship type that is prefixed to the table columns.
1786 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1787 $prefixColumn = $prefix . '_';
1788 $allKeys = array_keys($sqlColumns);
1789 $replaced = array();
1790 $headerRows = array_values($headerRows);
1792 // name map of the non standard fields in header rows & sql columns
1793 $mappingFields = array(
1794 'civicrm_primary_id' => 'id',
1795 'contact_source' => 'source',
1796 'current_employer_id' => 'employer_id',
1797 'contact_is_deleted' => 'is_deleted',
1798 'name' => 'address_name',
1799 'provider_id' => 'im_service_provider',
1800 'phone_type_id' => 'phone_type',
1803 //figure out which columns are to be replaced by which ones
1804 foreach ($sqlColumns as $columnNames => $dontCare) {
1805 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1806 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1809 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1811 if (!empty($sqlColumns[$householdColName])) {
1812 $replaced[$columnNames] = $householdColName;
1816 $query = "UPDATE $exportTempTable SET ";
1819 foreach ($replaced as $from => $to) {
1820 $clause[] = "$from = $to ";
1821 unset($sqlColumns[$to]);
1822 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1823 unset($headerRows[$key]);
1826 $query .= implode(",\n", $clause);
1827 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1829 CRM_Core_DAO
::executeQuery($query);
1831 //drop the table columns that store redundant household info
1832 $dropQuery = "ALTER TABLE $exportTempTable ";
1833 foreach ($replaced as $householdColumns) {
1834 $dropClause[] = " DROP $householdColumns ";
1836 $dropQuery .= implode(",\n", $dropClause);
1838 CRM_Core_DAO
::executeQuery($dropQuery);
1840 // also drop the temp table if exists
1841 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1842 CRM_Core_DAO
::executeQuery($sql);
1844 // clean up duplicate records
1846 CREATE TABLE {$exportTempTable}_temp SELECT *
1847 FROM {$exportTempTable}
1848 GROUP BY civicrm_primary_id ";
1850 CRM_Core_DAO
::executeQuery($query);
1852 $query = "DROP TABLE $exportTempTable";
1853 CRM_Core_DAO
::executeQuery($query);
1855 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1856 CRM_Core_DAO
::executeQuery($query);
1860 * @param $exportTempTable
1861 * @param $headerRows
1862 * @param $sqlColumns
1863 * @param $exportMode
1864 * @param null $saveFile
1865 * @param string $batchItems
1867 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1868 $writeHeader = TRUE;
1870 $limit = self
::EXPORT_ROW_COUNT
;
1872 $query = "SELECT * FROM $exportTempTable";
1875 $limitQuery = $query . "
1876 LIMIT $offset, $limit
1878 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1884 $componentDetails = array();
1885 while ($dao->fetch()) {
1888 foreach ($sqlColumns as $column => $dontCare) {
1889 $row[$column] = $dao->$column;
1891 $componentDetails[] = $row;
1893 if ($exportMode == 'financial') {
1894 $getExportFileName = 'CiviCRM Contribution Search';
1897 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1899 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1906 if ($saveFile && !empty($csvRows)) {
1907 $batchItems .= $csvRows;
1910 $writeHeader = FALSE;
1916 * Manipulate header rows for relationship fields.
1918 * @param $headerRows
1919 * @param $contactRelationshipTypes
1921 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1922 foreach ($headerRows as & $header) {
1923 $split = explode('-', $header);
1924 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1925 $split[0] = $relationTypeName;
1926 $header = implode('-', $split);
1932 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1933 * or have no street address
1934 * @param $exportTempTable
1935 * @param $headerRows
1936 * @param $sqlColumns
1937 * @param $exportParams
1939 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1940 $whereClause = array();
1942 if (array_key_exists('is_deceased', $sqlColumns)) {
1943 $whereClause[] = 'is_deceased = 1';
1946 if (array_key_exists('do_not_mail', $sqlColumns)) {
1947 $whereClause[] = 'do_not_mail = 1';
1950 if (array_key_exists('street_address', $sqlColumns)) {
1951 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1953 // check for supplemental_address_1
1954 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1955 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1956 'address_options', TRUE, NULL, TRUE
1958 if (!empty($addressOptions['supplemental_address_1'])) {
1959 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1960 // enclose it again, since we are doing an AND in between a set of ORs
1961 $addressWhereClause = "( $addressWhereClause )";
1965 $whereClause[] = $addressWhereClause;
1968 if (!empty($whereClause)) {
1969 $whereClause = implode(' OR ', $whereClause);
1972 FROM $exportTempTable
1973 WHERE {$whereClause}";
1974 CRM_Core_DAO
::singleValueQuery($query);
1977 // unset temporary columns that were added for postal mailing format
1978 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1979 $unsetKeys = array_keys($sqlColumns);
1980 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1981 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1982 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1989 * Build componentPayment fields.
1991 public static function componentPaymentFields() {
1992 static $componentPaymentFields;
1993 if (!isset($componentPaymentFields)) {
1994 $componentPaymentFields = array(
1995 'componentPaymentField_total_amount' => ts('Total Amount'),
1996 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1997 'componentPaymentField_received_date' => ts('Date Received'),
1998 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1999 'componentPaymentField_transaction_id' => ts('Transaction ID'),
2002 return $componentPaymentFields;
2006 * Set the definition for the header rows and sql columns based on the field to output.
2008 * @param string $field
2009 * @param array $headerRows
2010 * @param array $sqlColumns
2011 * Columns to go in the temp table.
2012 * @param CRM_Contact_BAO_Query $query
2013 * @param array|string $value
2014 * @param array $phoneTypes
2015 * @param array $imProviders
2016 * @param array $contactRelationshipTypes
2017 * @param string $relationQuery
2018 * @param array $selectedPaymentFields
2021 public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
2023 // Split campaign into 2 fields for id and title
2024 if (substr($field, -14) == 'campaign_title') {
2025 $headerRows[] = ts('Campaign Title');
2027 elseif (substr($field, -11) == 'campaign_id') {
2028 $headerRows[] = ts('Campaign ID');
2030 elseif (isset($query->_fields
[$field]['title'])) {
2031 $headerRows[] = $query->_fields
[$field]['title'];
2033 elseif ($field == 'phone_type_id') {
2034 $headerRows[] = ts('Phone Type');
2036 elseif ($field == 'provider_id') {
2037 $headerRows[] = ts('IM Service Provider');
2039 elseif (substr($field, 0, 5) == 'case_') {
2040 if ($query->_fields
['case'][$field]['title']) {
2041 $headerRows[] = $query->_fields
['case'][$field]['title'];
2043 elseif ($query->_fields
['activity'][$field]['title']) {
2044 $headerRows[] = $query->_fields
['activity'][$field]['title'];
2047 elseif (array_key_exists($field, $contactRelationshipTypes)) {
2048 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
2049 foreach ($value as $relationField => $relationValue) {
2050 // below block is same as primary block (duplicate)
2051 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
2052 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
2053 $headerName = $field . '-' . $relationField;
2056 if ($relationField == 'current_employer') {
2057 $headerName = $field . '-' . 'current_employer';
2060 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
2064 $headerRows[] = $headerName;
2066 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2068 elseif ($relationField == 'phone_type_id') {
2069 $headerName = $field . '-' . 'Phone Type';
2070 $headerRows[] = $headerName;
2071 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2073 elseif ($relationField == 'provider_id') {
2074 $headerName = $field . '-' . 'Im Service Provider';
2075 $headerRows[] = $headerName;
2076 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2078 elseif ($relationField == 'state_province_id') {
2079 $headerName = $field . '-' . 'state_province_id';
2080 $headerRows[] = $headerName;
2081 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2083 elseif (is_array($relationValue) && $relationField == 'location') {
2084 // fix header for location type case
2085 foreach ($relationValue as $ltype => $val) {
2086 foreach (array_keys($val) as $fld) {
2087 $type = explode('-', $fld);
2089 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
2091 if (!empty($type[1])) {
2092 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
2093 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
2095 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
2096 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
2099 $headerName = $field . '-' . $hdr;
2100 $headerRows[] = $headerName;
2101 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
2107 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
2108 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
2111 $headerRows[] = $field;
2114 self
::sqlColumnDefn($query, $sqlColumns, $field);
2116 return array($headerRows, $sqlColumns);
2120 * Get the various arrays that we use to structure our output.
2122 * The extraction of these has been moved to a separate function for clarity and so that
2123 * tests can be added - in particular on the $outputHeaders array.
2125 * However it still feels a bit like something that I'm too polite to write down and this should be seen
2126 * as a step on the refactoring path rather than how it should be.
2128 * @param array $returnProperties
2129 * @param CRM_Contact_BAO_Contact $query
2130 * @param array $phoneTypes
2131 * @param array $imProviders
2132 * @param array $contactRelationshipTypes
2133 * @param string $relationQuery
2134 * @param array $selectedPaymentFields
2136 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
2137 * alias for the field generated by BAO_Query object.
2138 * - headerRows Array of the column header strings to put in the csv header - non-associative.
2139 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
2140 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
2141 * I'm too embarassed to discuss here.
2143 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
2144 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
2145 * in the main DAO loop is done once per row & that coule be 100,000 times.)
2146 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
2147 * - a) the function used is more efficient or
2148 * - b) this code is old & outdated. Submit your answers to circular bin or better
2149 * yet find a way to comment them for posterity.
2151 public static function getExportStructureArrays($returnProperties, $query, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
2152 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
2154 foreach ($returnProperties as $key => $value) {
2155 if ($key != 'location' ||
!is_array($value)) {
2156 $outputColumns[$key] = $value;
2157 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2160 foreach ($value as $locationType => $locationFields) {
2161 foreach (array_keys($locationFields) as $locationFieldName) {
2162 $type = explode('-', $locationFieldName);
2164 $actualDBFieldName = $type[0];
2165 $outputFieldName = $locationType . '-' . $query->_fields
[$actualDBFieldName]['title'];
2166 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
2168 if (!empty($type[1])) {
2169 $daoFieldName .= "-" . $type[1];
2170 if ($actualDBFieldName == 'phone') {
2171 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
2173 elseif ($actualDBFieldName == 'im') {
2174 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
2177 if ($type[0] == 'im_provider') {
2178 // Warning: shame inducing hack.
2179 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
2181 self
::sqlColumnDefn($query, $sqlColumns, $outputFieldName);
2182 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2183 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
2184 $metadata[$daoFieldName] = array('context' => 'country');
2186 if ($actualDBFieldName == 'state_province') {
2187 $metadata[$daoFieldName] = array('context' => 'province');
2189 $outputColumns[$daoFieldName] = TRUE;
2194 return array($outputColumns, $headerRows, $sqlColumns, $metadata);