3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2018
35 * This class contains the functions for Component export
38 class CRM_Export_BAO_Export
{
39 // increase this number a lot to avoid making too many queries
40 // LIMIT is not much faster than a no LIMIT query
42 const EXPORT_ROW_COUNT
= 100000;
44 protected static $relationshipReturnProperties = [];
48 * @param $locationTypeFields
49 * @param $relationshipTypes
53 protected static function setRelationshipReturnProperties($value, $locationTypeFields, $relationshipTypes) {
54 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
55 $relPhoneTypeId = $relIMProviderId = NULL;
56 if (!empty($value[2])) {
57 $relationField = CRM_Utils_Array
::value(2, $value);
58 if (trim(CRM_Utils_Array
::value(3, $value))) {
59 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
62 $relLocTypeId = 'Primary';
65 if ($relationField == 'phone') {
66 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
68 elseif ($relationField == 'im') {
69 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
72 elseif (!empty($value[4])) {
73 $relationField = CRM_Utils_Array
::value(4, $value);
74 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
75 if ($relationField == 'phone') {
76 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
78 elseif ($relationField == 'im') {
79 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
82 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
83 if ($relPhoneTypeId) {
84 self
::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
86 elseif ($relIMProviderId) {
87 self
::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
90 self
::$relationshipReturnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
94 self
::$relationshipReturnProperties[$relationshipTypes][$relationField] = 1;
96 return array($relationField);
102 public static function getRelationshipReturnProperties() {
103 return self
::relationshipReturnProperties
;
107 * Get Querymode based on ExportMode
109 * @param int $exportMode
112 * @return string $Querymode
115 public static function getQueryMode($exportMode) {
116 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
118 switch ($exportMode) {
119 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
120 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
123 case CRM_Export_Form_Select
::EVENT_EXPORT
:
124 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
127 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
128 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
131 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
132 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
135 case CRM_Export_Form_Select
::CASE_EXPORT
:
136 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
139 case CRM_Export_Form_Select
::GRANT_EXPORT
:
140 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
143 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
144 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
151 * Get default return property for export based on mode
153 * @param int $exportMode
156 * @return string $property
157 * Default Return property
159 public static function defaultReturnProperty($exportMode) {
160 // hack to add default return property based on export mode
162 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
163 $property = 'contribution_id';
165 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
166 $property = 'participant_id';
168 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
169 $property = 'membership_id';
171 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
172 $property = 'pledge_id';
174 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
175 $property = 'case_id';
177 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
178 $property = 'grant_id';
180 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
181 $property = 'activity_id';
187 * Get Export component
189 * @param int $exportMode
192 * @return string $component
193 * CiviCRM Export Component
195 public static function exportComponent($exportMode) {
196 switch ($exportMode) {
197 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
198 $component = 'civicrm_contribution';
201 case CRM_Export_Form_Select
::EVENT_EXPORT
:
202 $component = 'civicrm_participant';
205 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
206 $component = 'civicrm_membership';
209 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
210 $component = 'civicrm_pledge';
213 case CRM_Export_Form_Select
::GRANT_EXPORT
:
214 $component = 'civicrm_grant';
221 * Get Query Group By Clause
222 * @param int $exportMode
224 * @param string $queryMode
226 * @param array $returnProperties
228 * @param object $query
229 * CRM_Contact_BAO_Query
231 * @return string $groupBy
234 public static function getGroupBy($exportMode, $queryMode, $returnProperties, $query) {
236 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
237 CRM_Utils_Array
::value('notes', $returnProperties) ||
239 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
241 $groupBy = "contact_a.id";
244 switch ($exportMode) {
245 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
246 $groupBy = 'civicrm_contribution.id';
247 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
248 // especial group by when soft credit columns are included
249 $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
253 case CRM_Export_Form_Select
::EVENT_EXPORT
:
254 $groupBy = 'civicrm_participant.id';
257 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
258 $groupBy = "civicrm_membership.id";
262 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
263 $groupBy = "civicrm_activity.id ";
266 if (!empty($groupBy)) {
267 if (!Civi
::settings()->get('searchPrimaryDetailsOnly')) {
268 CRM_Core_DAO
::disableFullGroupByMode();
270 $groupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($query->_select
, $groupBy);
277 * Define extra properties for the export based on query mode
279 * @param string $queryMode
281 * @return array $extraProperties
284 public static function defineExtraProperties($queryMode) {
285 switch ($queryMode) {
286 case CRM_Contact_BAO_Query
::MODE_EVENT
:
287 $paymentFields = TRUE;
288 $paymentTableId = 'participant_id';
289 $extraReturnProperties = array();
292 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
293 $paymentFields = TRUE;
294 $paymentTableId = 'membership_id';
295 $extraReturnProperties = array();
298 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
299 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
300 $paymentFields = TRUE;
301 $paymentTableId = 'pledge_payment_id';
304 case CRM_Contact_BAO_Query
::MODE_CASE
:
305 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
306 $paymentFields = FALSE;
307 $paymentTableId = '';
311 $paymentFields = FALSE;
312 $paymentTableId = '';
313 $extraReturnProperties = array();
315 $extraProperties = array(
316 'paymentFields' => $paymentFields,
317 'paymentTableId' => $paymentTableId,
318 'extraReturnProperties' => $extraReturnProperties,
320 return $extraProperties;
324 * Get the list the export fields.
326 * @param int $selectAll
327 * User preference while export.
330 * @param array $params
331 * Associated array of fields.
332 * @param string $order
334 * @param array $fields
335 * Associated array of fields.
336 * @param array $moreReturnProperties
337 * Additional return fields.
338 * @param int $exportMode
340 * @param string $componentClause
342 * @param string $componentTable
344 * @param bool $mergeSameAddress
345 * Merge records if they have same address.
346 * @param bool $mergeSameHousehold
347 * Merge records if they belong to the same household.
349 * @param array $exportParams
350 * @param string $queryOperator
353 * An array can be requested from within a unit test.
355 * @throws \CRM_Core_Exception
357 public static function exportComponents(
363 $moreReturnProperties = NULL,
364 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
365 $componentClause = NULL,
366 $componentTable = NULL,
367 $mergeSameAddress = FALSE,
368 $mergeSameHousehold = FALSE,
369 $exportParams = array(),
370 $queryOperator = 'AND'
373 $returnProperties = array();
374 $paymentFields = $selectedPaymentFields = FALSE;
376 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
377 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
378 // without manually testing the export of IM provider still works.
379 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
380 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
390 $queryMode = self
::getQueryMode($exportMode);
393 //construct return properties
394 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
395 $locationTypeFields = array(
397 'supplemental_address_1',
398 'supplemental_address_2',
399 'supplemental_address_3',
402 'postal_code_suffix',
412 foreach ($fields as $key => $value) {
413 $fieldName = CRM_Utils_Array
::value(1, $value);
418 if (array_key_exists($fieldName, $contactRelationshipTypes) && (!empty($value[2]) ||
!empty($value[4]))) {
419 self
::setRelationshipReturnProperties($value, $locationTypeFields, $fieldName);
420 // @todo we can later not add this to this array but maintain a separate array.
421 $returnProperties = array_merge($returnProperties, self
::$relationshipReturnProperties);
423 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
424 $locTypeId = $value[2];
425 if ($fieldName == 'phone') {
426 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
428 elseif ($fieldName == 'im') {
429 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
432 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
436 //hack to fix component fields
437 //revert mix of event_id and title
438 if ($fieldName == 'event_id') {
439 $returnProperties['event_id'] = 1;
442 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
443 array_key_exists($fieldName, self
::componentPaymentFields())
445 $selectedPaymentFields = TRUE;
446 $paymentTableId = 'participant_id';
447 $returnProperties[$fieldName] = 1;
450 $returnProperties[$fieldName] = 1;
454 $defaultExportMode = self
::defaultReturnProperty($exportMode);
455 if ($defaultExportMode) {
456 $returnProperties[$defaultExportMode] = 1;
461 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
462 foreach ($fields as $key => $var) {
463 if ($key && (substr($key, 0, 6) != 'custom')) {
465 $returnProperties[$key] = 1;
470 $returnProperties['location_type'] = 1;
471 $returnProperties['im_provider'] = 1;
472 $returnProperties['phone_type_id'] = 1;
473 $returnProperties['provider_id'] = 1;
474 $returnProperties['current_employer'] = 1;
477 $extraProperties = self
::defineExtraProperties($queryMode);
478 $paymentFields = $extraProperties['paymentFields'];
479 $extraReturnProperties = $extraProperties['extraReturnProperties'];
480 $paymentTableId = $extraProperties['paymentTableId'];
482 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
483 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
484 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
485 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
486 $componentReturnProperties = array_merge(
487 $componentReturnProperties,
488 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
490 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
492 if (!empty($extraReturnProperties)) {
493 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
496 // unset non exportable fields for components
497 $nonExpoFields = array(
501 'contribution_status_id',
503 'pledge_payment_status_id',
505 foreach ($nonExpoFields as $value) {
506 unset($returnProperties[$value]);
511 if ($mergeSameAddress) {
512 //make sure the addressee fields are selected
513 //while using merge same address feature
514 $returnProperties['addressee'] = 1;
515 $returnProperties['postal_greeting'] = 1;
516 $returnProperties['email_greeting'] = 1;
517 $returnProperties['street_name'] = 1;
518 $returnProperties['household_name'] = 1;
519 $returnProperties['street_address'] = 1;
520 $returnProperties['city'] = 1;
521 $returnProperties['state_province'] = 1;
523 // some columns are required for assistance incase they are not already present
524 $exportParams['merge_same_address']['temp_columns'] = array();
525 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
526 foreach ($tempColumns as $column) {
527 if (!array_key_exists($column, $returnProperties)) {
528 $returnProperties[$column] = 1;
529 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
530 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
535 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
536 // If an Additional Group is selected, then all contacts in that group are
537 // added to the export set (filtering out duplicates).
539 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";
540 CRM_Core_DAO
::executeQuery($query);
543 if ($moreReturnProperties) {
545 if (!empty($moreReturnProperties['group'])) {
546 unset($moreReturnProperties['group']);
547 $moreReturnProperties['groups'] = 1;
549 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
552 $exportParams['postal_mailing_export']['temp_columns'] = array();
553 if ($exportParams['exportOption'] == 2 &&
554 isset($exportParams['postal_mailing_export']) &&
555 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
557 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
558 foreach ($postalColumns as $column) {
559 if (!array_key_exists($column, $returnProperties)) {
560 $returnProperties[$column] = 1;
561 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
566 // rectify params to what proximity search expects if there is a value for prox_distance
568 if (!empty($params)) {
569 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
572 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
573 FALSE, FALSE, $queryMode,
574 FALSE, TRUE, TRUE, NULL, $queryOperator
579 $query->_sort
= $order;
580 list($select, $from, $where, $having) = $query->query();
582 if ($mergeSameHousehold == 1) {
583 if (empty($returnProperties['id'])) {
584 $returnProperties['id'] = 1;
587 //also merge Head of Household
588 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
589 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
591 foreach ($returnProperties as $key => $value) {
592 if (!array_key_exists($key, $contactRelationshipTypes)) {
593 $returnProperties[$relationKeyMOH][$key] = $value;
594 $returnProperties[$relationKeyHOH][$key] = $value;
598 unset($returnProperties[$relationKeyMOH]['location_type']);
599 unset($returnProperties[$relationKeyMOH]['im_provider']);
600 unset($returnProperties[$relationKeyHOH]['location_type']);
601 unset($returnProperties[$relationKeyHOH]['im_provider']);
604 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $contactRelationshipTypes, $returnProperties, $queryMode);
606 // make sure the groups stuff is included only if specifically specified
607 // by the fields param (CRM-1969), else we limit the contacts outputted to only
608 // ones that are part of a group
609 if (!empty($returnProperties['groups'])) {
610 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
611 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
612 // total hack for export, CRM-3618
613 $from = str_replace($oldClause,
619 if (!$selectAll && $componentTable) {
620 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
622 elseif ($componentClause) {
624 $where = "WHERE $componentClause";
627 $where .= " AND $componentClause";
631 // CRM-13982 - check if is deleted
632 $excludeTrashed = TRUE;
633 foreach ($params as $value) {
634 if ($value[0] == 'contact_is_deleted') {
635 $excludeTrashed = FALSE;
638 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
641 $where = "WHERE $trashClause";
644 $where .= " AND $trashClause";
647 $queryString = "$select $from $where $having";
649 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
651 $queryString .= $groupBy;
654 // always add contact_a.id to the ORDER clause
655 // so the order is deterministic
657 if (strpos('contact_a.id', $order) === FALSE) {
658 $order .= ", contact_a.id";
661 list($field, $dir) = explode(' ', $order, 2);
662 $field = trim($field);
663 if (!empty($returnProperties[$field])) {
665 $queryString .= " ORDER BY $order";
669 $addPaymentHeader = FALSE;
671 $paymentDetails = array();
672 if ($paymentFields ||
$selectedPaymentFields) {
674 // get payment related in for event and members
675 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
676 //get all payment headers.
677 // If we haven't selected specific payment fields, load in all the
679 if (!$selectedPaymentFields) {
680 $paymentHeaders = self
::componentPaymentFields();
681 if (!empty($paymentDetails)) {
682 $addPaymentHeader = TRUE;
685 // If we have selected specific payment fields, leave the payment headers
686 // as an empty array; the headers for each selected field will be added
689 $paymentHeaders = array();
691 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
694 $componentDetails = array();
697 $rowCount = self
::EXPORT_ROW_COUNT
;
699 // we write to temp table often to avoid using too much memory
704 // for CRM-3157 purposes
705 $i18n = CRM_Core_I18n
::singleton();
707 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $query, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
709 $limitReached = FALSE;
710 while (!$limitReached) {
711 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
712 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
713 // If this is less than our limit by the end of the iteration we do not need to run the query again to
714 // check if some remain.
715 $rowsThisIteration = 0;
717 while ($iterationDAO->fetch()) {
719 $rowsThisIteration++
;
721 $query->convertToPseudoNames($iterationDAO);
723 //first loop through output columns so that we return what is required, and in same order.
724 foreach ($outputColumns as $field => $value) {
726 // add im_provider to $dao object
727 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
728 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
731 //build row values (data)
733 if (property_exists($iterationDAO, $field)) {
734 $fieldValue = $iterationDAO->$field;
735 // to get phone type from phone type id
736 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
737 $fieldValue = $phoneTypes[$fieldValue];
739 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
740 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
742 elseif (strstr($field, 'master_id')) {
743 $masterAddressId = NULL;
744 if (isset($iterationDAO->$field)) {
745 $masterAddressId = $iterationDAO->$field;
747 // get display name of contact that address is shared.
748 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
752 if ($field == 'id') {
753 $row[$field] = $iterationDAO->contact_id
;
754 // special case for calculated field
756 elseif ($field == 'source_contact_id') {
757 $row[$field] = $iterationDAO->contact_id
;
759 elseif ($field == 'pledge_balance_amount') {
760 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
761 // special case for calculated field
763 elseif ($field == 'pledge_next_pay_amount') {
764 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
766 elseif (array_key_exists($field, $contactRelationshipTypes)) {
767 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
768 $relationQuery[$field]->convertToPseudoNames($relDAO);
769 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
771 elseif (isset($fieldValue) &&
774 //check for custom data
775 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
776 $row[$field] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
779 elseif (in_array($field, array(
784 //special case for greeting replacement
785 $fldValue = "{$field}_display";
786 $row[$field] = $iterationDAO->$fldValue;
789 //normal fields with a touch of CRM-3157
793 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
796 case 'state_province':
797 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
801 case 'preferred_communication_method':
802 case 'preferred_mail_format':
803 case 'communication_style':
804 $row[$field] = $i18n->crm_translate($fieldValue);
808 if (isset($metadata[$field])) {
809 // No I don't know why we do it this way & whether we could
810 // make better use of pseudoConstants.
811 if (!empty($metadata[$field]['context'])) {
812 $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
815 if (!empty($metadata[$field]['pseudoconstant'])) {
816 // This is not our normal syntax for pseudoconstants but I am a bit loath to
817 // call an external function until sure it is not increasing php processing given this
818 // may be iterated 100,000 times & we already have the $imProvider var loaded.
819 // That can be next refactor...
820 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
821 // but I have to reach a stable point....
822 $varName = $metadata[$field]['pseudoconstant']['var'];
824 $row[$field] = $labels[$fieldValue];
829 $row[$field] = $fieldValue;
834 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
835 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
836 $payFieldMapper = array(
837 'componentPaymentField_total_amount' => 'total_amount',
838 'componentPaymentField_contribution_status' => 'contribution_status',
839 'componentPaymentField_payment_instrument' => 'pay_instru',
840 'componentPaymentField_transaction_id' => 'trxn_id',
841 'componentPaymentField_received_date' => 'receive_date',
843 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
846 // if field is empty or null
851 // add payment headers if required
852 if ($addPaymentHeader && $paymentFields) {
853 // @todo rather than do this for every single row do it before the loop starts.
854 // where other header definitions take place.
855 $headerRows = array_merge($headerRows, $paymentHeaders);
856 foreach (array_keys($paymentHeaders) as $paymentHdr) {
857 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
862 $exportTempTable = self
::createTempTable($sqlColumns);
865 //build header only once
868 // If specific payment fields have been selected for export, payment
869 // data will already be in $row. Otherwise, add payment related
870 // information, if appropriate.
871 if ($addPaymentHeader) {
872 if (!$selectedPaymentFields) {
873 if ($paymentFields) {
874 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
875 if (!is_array($paymentData) ||
empty($paymentData)) {
876 $paymentData = $nullContributionDetails;
878 $row = array_merge($row, $paymentData);
880 elseif (!empty($paymentDetails)) {
881 $row = array_merge($row, $nullContributionDetails);
885 //remove organization name for individuals if it is set for current employer
886 if (!empty($row['contact_type']) &&
887 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
889 $row['organization_name'] = '';
892 // add component info
893 // write the row to a file
894 $componentDetails[] = $row;
896 // output every $tempRowCount rows
897 if ($count %
$tempRowCount == 0) {
898 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
899 $componentDetails = array();
902 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
903 $limitReached = TRUE;
905 $offset +
= $rowCount;
908 if ($exportTempTable) {
909 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
911 // if postalMailing option is checked, exclude contacts who are deceased, have
912 // "Do not mail" privacy setting, or have no street address
913 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
914 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
916 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
919 // do merge same address and merge same household processing
920 if ($mergeSameAddress) {
921 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
924 // merge the records if they have corresponding households
925 if ($mergeSameHousehold) {
926 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
927 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
931 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
933 // In order to be able to write a unit test against this function we need to suppress
934 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
935 if (empty($exportParams['suppress_csv_for_testing'])) {
936 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
939 // return tableName and sqlColumns in test context
940 return array($exportTempTable, $sqlColumns);
943 // delete the export temp table and component table
944 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
945 CRM_Core_DAO
::executeQuery($sql);
946 CRM_Core_DAO
::reenableFullGroupByMode();
947 CRM_Utils_System
::civiExit();
950 CRM_Core_DAO
::reenableFullGroupByMode();
951 throw new CRM_Core_Exception(ts('No records to export'));
956 * Name of the export file based on mode.
958 * @param string $output
966 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
968 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
969 return ts('CiviCRM Contact Search');
971 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
972 return ts('CiviCRM Contribution Search');
974 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
975 return ts('CiviCRM Member Search');
977 case CRM_Export_Form_Select
::EVENT_EXPORT
:
978 return ts('CiviCRM Participant Search');
980 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
981 return ts('CiviCRM Pledge Search');
983 case CRM_Export_Form_Select
::CASE_EXPORT
:
984 return ts('CiviCRM Case Search');
986 case CRM_Export_Form_Select
::GRANT_EXPORT
:
987 return ts('CiviCRM Grant Search');
989 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
990 return ts('CiviCRM Activity Search');
995 * Handle import error file creation.
997 public static function invoke() {
998 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
999 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
1000 if (empty($parserName) ||
empty($type)) {
1004 // clean and ensure parserName is a valid string
1005 $parserName = CRM_Utils_String
::munge($parserName);
1006 $parserClass = explode('_', $parserName);
1008 // make sure parserClass is in the CRM namespace and
1009 // at least 3 levels deep
1010 if ($parserClass[0] == 'CRM' &&
1011 count($parserClass) >= 3
1013 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
1014 // ensure the functions exists
1015 if (method_exists($parserName, 'errorFileName') &&
1016 method_exists($parserName, 'saveFileName')
1018 $errorFileName = $parserName::errorFileName($type);
1019 $saveFileName = $parserName::saveFileName($type);
1020 if (!empty($errorFileName) && !empty($saveFileName)) {
1021 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
1022 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
1023 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
1024 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1025 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1027 readfile($errorFileName);
1031 CRM_Utils_System
::civiExit();
1035 * @param $customSearchClass
1036 * @param $formValues
1039 public static function exportCustom($customSearchClass, $formValues, $order) {
1040 $ext = CRM_Extension_System
::singleton()->getMapper();
1041 if (!$ext->isExtensionClass($customSearchClass)) {
1042 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1045 require_once $ext->classToPath($customSearchClass);
1047 $search = new $customSearchClass($formValues);
1049 $includeContactIDs = FALSE;
1050 if ($formValues['radio_ts'] == 'ts_sel') {
1051 $includeContactIDs = TRUE;
1054 $sql = $search->all(0, 0, $order, $includeContactIDs);
1056 $columns = $search->columns();
1058 $header = array_keys($columns);
1059 $fields = array_values($columns);
1062 $dao = CRM_Core_DAO
::executeQuery($sql);
1064 if (method_exists($search, 'alterRow')) {
1067 while ($dao->fetch()) {
1070 foreach ($fields as $field) {
1071 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
1072 $row[$field] = $dao->$unqualified_field;
1075 $search->alterRow($row);
1080 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1081 CRM_Utils_System
::civiExit();
1086 * @param $sqlColumns
1089 public static function sqlColumnDefn($query, &$sqlColumns, $field) {
1090 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1094 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1095 if ($fieldName == 'id') {
1096 $fieldName = 'civicrm_primary_id';
1099 // early exit for master_id, CRM-12100
1100 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1101 // also for current_employer, CRM-16939
1102 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1103 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1107 if (substr($fieldName, -11) == 'campaign_id') {
1109 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1113 $lookUp = array('prefix_id', 'suffix_id');
1114 // set the sql columns
1115 if (isset($query->_fields
[$field]['type'])) {
1116 switch ($query->_fields
[$field]['type']) {
1117 case CRM_Utils_Type
::T_INT
:
1118 case CRM_Utils_Type
::T_BOOLEAN
:
1119 if (in_array($field, $lookUp)) {
1120 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1123 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1127 case CRM_Utils_Type
::T_STRING
:
1128 if (isset($query->_fields
[$field]['maxlength'])) {
1129 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1132 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1136 case CRM_Utils_Type
::T_TEXT
:
1137 case CRM_Utils_Type
::T_LONGTEXT
:
1138 case CRM_Utils_Type
::T_BLOB
:
1139 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1140 $sqlColumns[$fieldName] = "$fieldName longtext";
1143 case CRM_Utils_Type
::T_FLOAT
:
1144 case CRM_Utils_Type
::T_ENUM
:
1145 case CRM_Utils_Type
::T_DATE
:
1146 case CRM_Utils_Type
::T_TIME
:
1147 case CRM_Utils_Type
::T_TIMESTAMP
:
1148 case CRM_Utils_Type
::T_MONEY
:
1149 case CRM_Utils_Type
::T_EMAIL
:
1150 case CRM_Utils_Type
::T_URL
:
1151 case CRM_Utils_Type
::T_CCNUM
:
1153 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1158 if (substr($fieldName, -3, 3) == '_id') {
1159 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1161 elseif (substr($fieldName, -5, 5) == '_note') {
1162 $sqlColumns[$fieldName] = "$fieldName text";
1165 $changeFields = array(
1171 if (in_array($fieldName, $changeFields)) {
1172 $sqlColumns[$fieldName] = "$fieldName text";
1175 // set the sql columns for custom data
1176 if (isset($query->_fields
[$field]['data_type'])) {
1178 switch ($query->_fields
[$field]['data_type']) {
1180 // May be option labels, which could be up to 512 characters
1181 $length = max(512, CRM_Utils_Array
::value('text_length', $query->_fields
[$field]));
1182 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1186 case 'StateProvince':
1188 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1192 $sqlColumns[$fieldName] = "$fieldName text";
1196 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1201 $sqlColumns[$fieldName] = "$fieldName text";
1209 * @param string $tableName
1211 * @param $sqlColumns
1213 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1214 if (empty($details)) {
1223 $id = CRM_Core_DAO
::singleValueQuery($sql);
1228 $sqlClause = array();
1230 foreach ($details as $dontCare => $row) {
1232 $valueString = array($id);
1233 foreach ($row as $dontCare => $value) {
1234 if (empty($value)) {
1235 $valueString[] = "''";
1238 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1241 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1244 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1246 $sqlValueString = implode(",\n", $sqlClause);
1249 INSERT INTO $tableName $sqlColumnString
1250 VALUES $sqlValueString
1252 CRM_Core_DAO
::executeQuery($sql);
1256 * @param $sqlColumns
1260 public static function createTempTable(&$sqlColumns) {
1261 //creating a temporary table for the search result that need be exported
1262 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
1264 // also create the sql table
1265 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1266 CRM_Core_DAO
::executeQuery($sql);
1269 CREATE TABLE {$exportTempTable} (
1270 id int unsigned NOT NULL AUTO_INCREMENT,
1272 $sql .= implode(",\n", array_values($sqlColumns));
1277 // add indexes for street_address and household_name if present
1278 $addIndices = array(
1281 'civicrm_primary_id',
1284 foreach ($addIndices as $index) {
1285 if (isset($sqlColumns[$index])) {
1287 INDEX index_{$index}( $index )
1293 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1296 CRM_Core_DAO
::executeQuery($sql);
1297 return $exportTempTable;
1301 * @param string $tableName
1302 * @param $headerRows
1303 * @param $sqlColumns
1304 * @param array $exportParams
1306 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1307 // check if any records are present based on if they have used shared address feature,
1308 // and not based on if city / state .. matches.
1310 SELECT r1.id as copy_id,
1311 r1.civicrm_primary_id as copy_contact_id,
1312 r1.addressee as copy_addressee,
1313 r1.addressee_id as copy_addressee_id,
1314 r1.postal_greeting as copy_postal_greeting,
1315 r1.postal_greeting_id as copy_postal_greeting_id,
1317 r2.civicrm_primary_id as master_contact_id,
1318 r2.postal_greeting as master_postal_greeting,
1319 r2.postal_greeting_id as master_postal_greeting_id,
1320 r2.addressee as master_addressee,
1321 r2.addressee_id as master_addressee_id
1323 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1324 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1326 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1328 // find all the records that have the same street address BUT not in a household
1329 // require match on city and state as well
1331 SELECT r1.id as master_id,
1332 r1.civicrm_primary_id as master_contact_id,
1333 r1.postal_greeting as master_postal_greeting,
1334 r1.postal_greeting_id as master_postal_greeting_id,
1335 r1.addressee as master_addressee,
1336 r1.addressee_id as master_addressee_id,
1338 r2.civicrm_primary_id as copy_contact_id,
1339 r2.postal_greeting as copy_postal_greeting,
1340 r2.postal_greeting_id as copy_postal_greeting_id,
1341 r2.addressee as copy_addressee,
1342 r2.addressee_id as copy_addressee_id
1344 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1345 r1.city = r2.city AND
1346 r1.state_province_id = r2.state_province_id )
1347 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1348 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1349 AND ( r1.street_address != '' )
1353 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1355 // unset ids from $merge already present in $linkedMerge
1356 foreach ($linkedMerge as $masterID => $values) {
1357 $keys = array($masterID);
1358 $keys = array_merge($keys, array_keys($values['copy']));
1359 foreach ($merge as $mid => $vals) {
1360 if (in_array($mid, $keys)) {
1361 unset($merge[$mid]);
1364 foreach ($values['copy'] as $copyId) {
1365 if (in_array($copyId, $keys)) {
1366 unset($merge[$mid]['copy'][$copyId]);
1372 $merge = $merge +
$linkedMerge;
1374 foreach ($merge as $masterID => $values) {
1377 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1381 1 => array($values['addressee'], 'String'),
1382 2 => array($values['postalGreeting'], 'String'),
1383 3 => array($values['emailGreeting'], 'String'),
1384 4 => array($masterID, 'Integer'),
1386 CRM_Core_DAO
::executeQuery($sql, $params);
1388 // delete all copies
1389 $deleteIDs = array_keys($values['copy']);
1390 $deleteIDString = implode(',', $deleteIDs);
1392 DELETE FROM $tableName
1393 WHERE id IN ( $deleteIDString )
1395 CRM_Core_DAO
::executeQuery($sql);
1398 // unset temporary columns that were added for postal mailing format
1399 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1400 $unsetKeys = array_keys($sqlColumns);
1401 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1402 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1403 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1410 * @param int $contactId
1411 * @param array $exportParams
1415 public static function _replaceMergeTokens($contactId, $exportParams) {
1416 $greetings = array();
1419 $greetingFields = array(
1423 foreach ($greetingFields as $greeting) {
1424 if (!empty($exportParams[$greeting])) {
1425 $greetingLabel = $exportParams[$greeting];
1426 if (empty($contact)) {
1431 $contact = civicrm_api('contact', 'get', $values);
1433 if (!empty($contact['is_error'])) {
1436 $contact = $contact['values'][$contact['id']];
1439 $tokens = array('contact' => $greetingLabel);
1440 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1447 * The function unsets static part of the string, if token is the dynamic part.
1449 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1450 * i.e 'Hello Alan' => converted to => 'Alan'
1452 * @param string $parsedString
1453 * @param string $defaultGreeting
1454 * @param bool $addressMergeGreetings
1455 * @param string $greetingType
1459 public static function _trimNonTokens(
1460 &$parsedString, $defaultGreeting,
1461 $addressMergeGreetings, $greetingType = 'postal_greeting'
1463 if (!empty($addressMergeGreetings[$greetingType])) {
1464 $greetingLabel = $addressMergeGreetings[$greetingType];
1466 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1468 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1469 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1470 foreach ($stringsToBeReplaced as $key => $string) {
1471 // to keep one space
1472 $stringsToBeReplaced[$key] = ltrim($string);
1474 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1476 return $parsedString;
1481 * @param array $exportParams
1482 * @param bool $sharedAddress
1486 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1487 static $contactGreetingTokens = array();
1489 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1490 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1492 $merge = $parents = array();
1493 $dao = CRM_Core_DAO
::executeQuery($sql);
1495 while ($dao->fetch()) {
1496 $masterID = $dao->master_id
;
1497 $copyID = $dao->copy_id
;
1498 $masterPostalGreeting = $dao->master_postal_greeting
;
1499 $masterAddressee = $dao->master_addressee
;
1500 $copyAddressee = $dao->copy_addressee
;
1502 if (!$sharedAddress) {
1503 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1504 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1506 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1507 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1509 $masterAddressee = CRM_Utils_Array
::value('addressee',
1510 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1513 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1514 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1516 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1517 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1519 $copyAddressee = CRM_Utils_Array
::value('addressee',
1520 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1524 if (!isset($merge[$masterID])) {
1525 // check if this is an intermediate child
1526 // this happens if there are 3 or more matches a,b, c
1527 // the above query will return a, b / a, c / b, c
1528 // we might be doing a bit more work, but for now its ok, unless someone
1529 // knows how to fix the query above
1530 if (isset($parents[$masterID])) {
1531 $masterID = $parents[$masterID];
1534 $merge[$masterID] = array(
1535 'addressee' => $masterAddressee,
1537 'postalGreeting' => $masterPostalGreeting,
1539 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1542 $parents[$copyID] = $masterID;
1544 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1546 if (!empty($exportParams['postal_greeting_other']) &&
1547 count($merge[$masterID]['copy']) >= 1
1549 // use static greetings specified if no of contacts > 2
1550 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1552 elseif ($copyPostalGreeting) {
1553 self
::_trimNonTokens($copyPostalGreeting,
1554 $postalOptions[$dao->copy_postal_greeting_id
],
1557 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1558 // if there happens to be a duplicate, remove it
1559 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1562 if (!empty($exportParams['addressee_other']) &&
1563 count($merge[$masterID]['copy']) >= 1
1565 // use static greetings specified if no of contacts > 2
1566 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1568 elseif ($copyAddressee) {
1569 self
::_trimNonTokens($copyAddressee,
1570 $addresseeOptions[$dao->copy_addressee_id
],
1571 $exportParams, 'addressee'
1573 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1576 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1583 * Merge household record into the individual record
1586 * @param string $exportTempTable
1587 * Temporary temp table that stores the records.
1588 * @param array $headerRows
1589 * Array of headers for the export file.
1590 * @param array $sqlColumns
1591 * Array of names of the table columns of the temp table.
1592 * @param string $prefix
1593 * Name of the relationship type that is prefixed to the table columns.
1595 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1596 $prefixColumn = $prefix . '_';
1597 $allKeys = array_keys($sqlColumns);
1598 $replaced = array();
1599 $headerRows = array_values($headerRows);
1601 // name map of the non standard fields in header rows & sql columns
1602 $mappingFields = array(
1603 'civicrm_primary_id' => 'id',
1604 'contact_source' => 'source',
1605 'current_employer_id' => 'employer_id',
1606 'contact_is_deleted' => 'is_deleted',
1607 'name' => 'address_name',
1608 'provider_id' => 'im_service_provider',
1609 'phone_type_id' => 'phone_type',
1612 //figure out which columns are to be replaced by which ones
1613 foreach ($sqlColumns as $columnNames => $dontCare) {
1614 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1615 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1618 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1620 if (!empty($sqlColumns[$householdColName])) {
1621 $replaced[$columnNames] = $householdColName;
1625 $query = "UPDATE $exportTempTable SET ";
1628 foreach ($replaced as $from => $to) {
1629 $clause[] = "$from = $to ";
1630 unset($sqlColumns[$to]);
1631 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1632 unset($headerRows[$key]);
1635 $query .= implode(",\n", $clause);
1636 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1638 CRM_Core_DAO
::executeQuery($query);
1640 //drop the table columns that store redundant household info
1641 $dropQuery = "ALTER TABLE $exportTempTable ";
1642 foreach ($replaced as $householdColumns) {
1643 $dropClause[] = " DROP $householdColumns ";
1645 $dropQuery .= implode(",\n", $dropClause);
1647 CRM_Core_DAO
::executeQuery($dropQuery);
1649 // also drop the temp table if exists
1650 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1651 CRM_Core_DAO
::executeQuery($sql);
1653 // clean up duplicate records
1655 CREATE TABLE {$exportTempTable}_temp SELECT *
1656 FROM {$exportTempTable}
1657 GROUP BY civicrm_primary_id ";
1659 CRM_Core_DAO
::executeQuery($query);
1661 $query = "DROP TABLE $exportTempTable";
1662 CRM_Core_DAO
::executeQuery($query);
1664 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1665 CRM_Core_DAO
::executeQuery($query);
1669 * @param $exportTempTable
1670 * @param $headerRows
1671 * @param $sqlColumns
1672 * @param $exportMode
1673 * @param null $saveFile
1674 * @param string $batchItems
1676 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1677 $writeHeader = TRUE;
1679 $limit = self
::EXPORT_ROW_COUNT
;
1681 $query = "SELECT * FROM $exportTempTable";
1684 $limitQuery = $query . "
1685 LIMIT $offset, $limit
1687 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1693 $componentDetails = array();
1694 while ($dao->fetch()) {
1697 foreach ($sqlColumns as $column => $dontCare) {
1698 $row[$column] = $dao->$column;
1700 $componentDetails[] = $row;
1702 if ($exportMode == 'financial') {
1703 $getExportFileName = 'CiviCRM Contribution Search';
1706 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1708 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1715 if ($saveFile && !empty($csvRows)) {
1716 $batchItems .= $csvRows;
1719 $writeHeader = FALSE;
1725 * Manipulate header rows for relationship fields.
1727 * @param $headerRows
1728 * @param $contactRelationshipTypes
1730 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1731 foreach ($headerRows as & $header) {
1732 $split = explode('-', $header);
1733 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1734 $split[0] = $relationTypeName;
1735 $header = implode('-', $split);
1741 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1742 * or have no street address
1743 * @param $exportTempTable
1744 * @param $headerRows
1745 * @param $sqlColumns
1746 * @param $exportParams
1748 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1749 $whereClause = array();
1751 if (array_key_exists('is_deceased', $sqlColumns)) {
1752 $whereClause[] = 'is_deceased = 1';
1755 if (array_key_exists('do_not_mail', $sqlColumns)) {
1756 $whereClause[] = 'do_not_mail = 1';
1759 if (array_key_exists('street_address', $sqlColumns)) {
1760 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1762 // check for supplemental_address_1
1763 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1764 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1765 'address_options', TRUE, NULL, TRUE
1767 if (!empty($addressOptions['supplemental_address_1'])) {
1768 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1769 // enclose it again, since we are doing an AND in between a set of ORs
1770 $addressWhereClause = "( $addressWhereClause )";
1774 $whereClause[] = $addressWhereClause;
1777 if (!empty($whereClause)) {
1778 $whereClause = implode(' OR ', $whereClause);
1781 FROM $exportTempTable
1782 WHERE {$whereClause}";
1783 CRM_Core_DAO
::singleValueQuery($query);
1786 // unset temporary columns that were added for postal mailing format
1787 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1788 $unsetKeys = array_keys($sqlColumns);
1789 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1790 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1791 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1798 * Build componentPayment fields.
1800 public static function componentPaymentFields() {
1801 static $componentPaymentFields;
1802 if (!isset($componentPaymentFields)) {
1803 $componentPaymentFields = array(
1804 'componentPaymentField_total_amount' => ts('Total Amount'),
1805 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1806 'componentPaymentField_received_date' => ts('Date Received'),
1807 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1808 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1811 return $componentPaymentFields;
1815 * Set the definition for the header rows and sql columns based on the field to output.
1817 * @param string $field
1818 * @param array $headerRows
1819 * @param array $sqlColumns
1820 * Columns to go in the temp table.
1821 * @param CRM_Contact_BAO_Query $query
1822 * @param array|string $value
1823 * @param array $phoneTypes
1824 * @param array $imProviders
1825 * @param array $contactRelationshipTypes
1826 * @param string $relationQuery
1827 * @param array $selectedPaymentFields
1830 public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
1832 // Split campaign into 2 fields for id and title
1833 if (substr($field, -14) == 'campaign_title') {
1834 $headerRows[] = ts('Campaign Title');
1836 elseif (substr($field, -11) == 'campaign_id') {
1837 $headerRows[] = ts('Campaign ID');
1839 elseif (isset($query->_fields
[$field]['title'])) {
1840 $headerRows[] = $query->_fields
[$field]['title'];
1842 elseif ($field == 'phone_type_id') {
1843 $headerRows[] = ts('Phone Type');
1845 elseif ($field == 'provider_id') {
1846 $headerRows[] = ts('IM Service Provider');
1848 elseif (substr($field, 0, 5) == 'case_' && $query->_fields
['case'][$field]['title']) {
1849 $headerRows[] = $query->_fields
['case'][$field]['title'];
1851 elseif (array_key_exists($field, $contactRelationshipTypes)) {
1852 foreach ($value as $relationField => $relationValue) {
1853 // below block is same as primary block (duplicate)
1854 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
1855 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
1856 $headerName = $field . '-' . $relationField;
1859 if ($relationField == 'current_employer') {
1860 $headerName = $field . '-' . 'current_employer';
1863 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
1867 $headerRows[] = $headerName;
1869 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1871 elseif ($relationField == 'phone_type_id') {
1872 $headerName = $field . '-' . 'Phone Type';
1873 $headerRows[] = $headerName;
1874 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1876 elseif ($relationField == 'provider_id') {
1877 $headerName = $field . '-' . 'Im Service Provider';
1878 $headerRows[] = $headerName;
1879 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1881 elseif ($relationField == 'state_province_id') {
1882 $headerName = $field . '-' . 'state_province_id';
1883 $headerRows[] = $headerName;
1884 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1886 elseif (is_array($relationValue) && $relationField == 'location') {
1887 // fix header for location type case
1888 foreach ($relationValue as $ltype => $val) {
1889 foreach (array_keys($val) as $fld) {
1890 $type = explode('-', $fld);
1892 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
1894 if (!empty($type[1])) {
1895 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1896 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1898 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1899 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1902 $headerName = $field . '-' . $hdr;
1903 $headerRows[] = $headerName;
1904 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1909 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1911 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1912 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1915 $headerRows[] = $field;
1918 self
::sqlColumnDefn($query, $sqlColumns, $field);
1920 return array($headerRows, $sqlColumns);
1924 * Get the various arrays that we use to structure our output.
1926 * The extraction of these has been moved to a separate function for clarity and so that
1927 * tests can be added - in particular on the $outputHeaders array.
1929 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1930 * as a step on the refactoring path rather than how it should be.
1932 * @param array $returnProperties
1933 * @param CRM_Contact_BAO_Contact $query
1934 * @param array $contactRelationshipTypes
1935 * @param string $relationQuery
1936 * @param array $selectedPaymentFields
1938 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1939 * alias for the field generated by BAO_Query object.
1940 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1941 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1942 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1943 * I'm too embarassed to discuss here.
1945 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1946 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1947 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1948 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1949 * - a) the function used is more efficient or
1950 * - b) this code is old & outdated. Submit your answers to circular bin or better
1951 * yet find a way to comment them for posterity.
1953 public static function getExportStructureArrays($returnProperties, $query, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
1954 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1955 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1956 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1958 foreach ($returnProperties as $key => $value) {
1959 if ($key != 'location' ||
!is_array($value)) {
1960 $outputColumns[$key] = $value;
1961 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
1964 foreach ($value as $locationType => $locationFields) {
1965 foreach (array_keys($locationFields) as $locationFieldName) {
1966 $type = explode('-', $locationFieldName);
1968 $actualDBFieldName = $type[0];
1969 $outputFieldName = $locationType . '-' . $query->_fields
[$actualDBFieldName]['title'];
1970 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1972 if (!empty($type[1])) {
1973 $daoFieldName .= "-" . $type[1];
1974 if ($actualDBFieldName == 'phone') {
1975 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1977 elseif ($actualDBFieldName == 'im') {
1978 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1981 if ($type[0] == 'im_provider') {
1982 // Warning: shame inducing hack.
1983 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1985 self
::sqlColumnDefn($query, $sqlColumns, $outputFieldName);
1986 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
1987 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1988 $metadata[$daoFieldName] = array('context' => 'country');
1990 if ($actualDBFieldName == 'state_province') {
1991 $metadata[$daoFieldName] = array('context' => 'province');
1993 $outputColumns[$daoFieldName] = TRUE;
1998 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
2002 * Get the values of linked household contact.
2004 * @param CRM_Core_DAO $relDAO
2005 * @param array $value
2006 * @param string $field
2009 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
2010 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
2011 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
2012 $i18n = CRM_Core_I18n
::singleton();
2013 foreach ($value as $relationField => $relationValue) {
2014 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
2015 $fieldValue = $relDAO->$relationField;
2016 if ($relationField == 'phone_type_id') {
2017 $fieldValue = $phoneTypes[$relationValue];
2019 elseif ($relationField == 'provider_id') {
2020 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
2023 elseif (is_object($relDAO) && in_array($relationField, array(
2029 //special case for greeting replacement
2030 $fldValue = "{$relationField}_display";
2031 $fieldValue = $relDAO->$fldValue;
2034 elseif (is_object($relDAO) && $relationField == 'state_province') {
2035 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
2037 elseif (is_object($relDAO) && $relationField == 'country') {
2038 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
2043 $field = $field . '_';
2044 $relPrefix = $field . $relationField;
2046 if (is_object($relDAO) && $relationField == 'id') {
2047 $row[$relPrefix] = $relDAO->contact_id
;
2049 elseif (is_array($relationValue) && $relationField == 'location') {
2050 foreach ($relationValue as $ltype => $val) {
2051 foreach (array_keys($val) as $fld) {
2052 $type = explode('-', $fld);
2053 $fldValue = "{$ltype}-" . $type[0];
2054 if (!empty($type[1])) {
2055 $fldValue .= "-" . $type[1];
2057 // CRM-3157: localise country, region (both have ‘country’ context)
2058 // and state_province (‘province’ context)
2060 case (!is_object($relDAO)):
2061 $row[$field . '_' . $fldValue] = '';
2064 case in_array('country', $type):
2065 case in_array('world_region', $type):
2066 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2067 array('context' => 'country')
2071 case in_array('state_province', $type):
2072 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2073 array('context' => 'province')
2078 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2084 elseif (isset($fieldValue) && $fieldValue != '') {
2085 //check for custom data
2086 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
2087 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2090 //normal relationship fields
2091 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2092 switch ($relationField) {
2094 case 'world_region':
2095 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
2098 case 'state_province':
2099 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
2103 $row[$relPrefix] = $fieldValue;
2109 // if relation field is empty or null
2110 $row[$relPrefix] = '';
2116 * Get the ids that we want to get related contact details for.
2119 * @param int $exportMode
2123 protected static function getIDsForRelatedContact($ids, $exportMode) {
2124 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
2127 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
2129 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
2130 $dao = CRM_Core_DAO
::executeQuery("
2131 SELECT contact_id FROM civicrm_activity_contact
2132 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
2133 record_type_id = {$sourceID}
2136 while ($dao->fetch()) {
2137 $relIDs[] = $dao->contact_id
;
2141 $component = self
::exportComponent($exportMode);
2143 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
2144 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
2147 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
2154 * @param $exportMode
2155 * @param $componentTable
2156 * @param $contactRelationshipTypes
2157 * @param $returnProperties
2161 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $contactRelationshipTypes, $returnProperties, $queryMode) {
2162 $allRelContactArray = $relationQuery = array();
2164 foreach ($contactRelationshipTypes as $rel => $dnt) {
2165 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
2166 $allRelContactArray[$rel] = array();
2167 // build Query for each relationship
2168 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
2169 NULL, FALSE, FALSE, $queryMode
2171 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
2173 list($id, $direction) = explode('_', $rel, 2);
2174 // identify the relationship direction
2175 $contactA = 'contact_id_a';
2176 $contactB = 'contact_id_b';
2177 if ($direction == 'b_a') {
2178 $contactA = 'contact_id_b';
2179 $contactB = 'contact_id_a';
2181 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
2183 $relationshipJoin = $relationshipClause = '';
2184 if (!$selectAll && $componentTable) {
2185 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
2187 elseif (!empty($relIDs)) {
2188 $relID = implode(',', $relIDs);
2189 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
2192 $relationFrom = " {$relationFrom}
2193 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
2194 {$relationshipJoin} ";
2196 //check for active relationship status only
2197 $today = date('Ymd');
2198 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
2199 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
2200 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
2201 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
2202 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
2204 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
2205 while ($allRelContactDAO->fetch()) {
2206 //FIX Me: Migrate this to table rather than array
2207 // build the array of all related contacts
2208 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
2210 $allRelContactDAO->free();
2213 return array($relationQuery, $allRelContactArray);