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 $allRelContactArray = $relationQuery = array();
606 foreach ($contactRelationshipTypes as $rel => $dnt) {
607 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
608 $allRelContactArray[$rel] = array();
609 // build Query for each relationship
610 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
611 NULL, FALSE, FALSE, $queryMode
613 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
615 list($id, $direction) = explode('_', $rel, 2);
616 // identify the relationship direction
617 $contactA = 'contact_id_a';
618 $contactB = 'contact_id_b';
619 if ($direction == 'b_a') {
620 $contactA = 'contact_id_b';
621 $contactB = 'contact_id_a';
623 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
626 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
627 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
628 $dao = CRM_Core_DAO
::executeQuery("
629 SELECT contact_id FROM civicrm_activity_contact
630 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
631 record_type_id = {$sourceID}
634 while ($dao->fetch()) {
635 $relIDs[] = $dao->contact_id
;
639 $component = self
::exportComponent($exportMode);
641 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
642 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
645 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
649 $relationshipJoin = $relationshipClause = '';
650 if (!$selectAll && $componentTable) {
651 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
653 elseif (!empty($relIDs)) {
654 $relID = implode(',', $relIDs);
655 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
658 $relationFrom = " {$relationFrom}
659 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
660 {$relationshipJoin} ";
662 //check for active relationship status only
663 $today = date('Ymd');
664 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
665 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
666 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
667 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
668 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
670 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
671 while ($allRelContactDAO->fetch()) {
672 //FIX Me: Migrate this to table rather than array
673 // build the array of all related contacts
674 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
676 $allRelContactDAO->free();
680 // make sure the groups stuff is included only if specifically specified
681 // by the fields param (CRM-1969), else we limit the contacts outputted to only
682 // ones that are part of a group
683 if (!empty($returnProperties['groups'])) {
684 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
685 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
686 // total hack for export, CRM-3618
687 $from = str_replace($oldClause,
693 if (!$selectAll && $componentTable) {
694 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
696 elseif ($componentClause) {
698 $where = "WHERE $componentClause";
701 $where .= " AND $componentClause";
705 // CRM-13982 - check if is deleted
706 $excludeTrashed = TRUE;
707 foreach ($params as $value) {
708 if ($value[0] == 'contact_is_deleted') {
709 $excludeTrashed = FALSE;
712 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
715 $where = "WHERE $trashClause";
718 $where .= " AND $trashClause";
721 $queryString = "$select $from $where $having";
723 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
725 $queryString .= $groupBy;
728 // always add contact_a.id to the ORDER clause
729 // so the order is deterministic
731 if (strpos('contact_a.id', $order) === FALSE) {
732 $order .= ", contact_a.id";
735 list($field, $dir) = explode(' ', $order, 2);
736 $field = trim($field);
737 if (!empty($returnProperties[$field])) {
739 $queryString .= " ORDER BY $order";
743 $addPaymentHeader = FALSE;
745 $paymentDetails = array();
746 if ($paymentFields ||
$selectedPaymentFields) {
748 // get payment related in for event and members
749 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
750 //get all payment headers.
751 // If we haven't selected specific payment fields, load in all the
753 if (!$selectedPaymentFields) {
754 $paymentHeaders = self
::componentPaymentFields();
755 if (!empty($paymentDetails)) {
756 $addPaymentHeader = TRUE;
759 // If we have selected specific payment fields, leave the payment headers
760 // as an empty array; the headers for each selected field will be added
763 $paymentHeaders = array();
765 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
768 $componentDetails = array();
771 $rowCount = self
::EXPORT_ROW_COUNT
;
773 // we write to temp table often to avoid using too much memory
778 // for CRM-3157 purposes
779 $i18n = CRM_Core_I18n
::singleton();
781 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $query, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
783 $limitReached = FALSE;
784 while (!$limitReached) {
785 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
786 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
787 // If this is less than our limit by the end of the iteration we do not need to run the query again to
788 // check if some remain.
789 $rowsThisIteration = 0;
791 while ($iterationDAO->fetch()) {
793 $rowsThisIteration++
;
795 $query->convertToPseudoNames($iterationDAO);
797 //first loop through output columns so that we return what is required, and in same order.
798 foreach ($outputColumns as $field => $value) {
800 // add im_provider to $dao object
801 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
802 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
805 //build row values (data)
807 if (property_exists($iterationDAO, $field)) {
808 $fieldValue = $iterationDAO->$field;
809 // to get phone type from phone type id
810 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
811 $fieldValue = $phoneTypes[$fieldValue];
813 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
814 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
816 elseif (strstr($field, 'master_id')) {
817 $masterAddressId = NULL;
818 if (isset($iterationDAO->$field)) {
819 $masterAddressId = $iterationDAO->$field;
821 // get display name of contact that address is shared.
822 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
826 if ($field == 'id') {
827 $row[$field] = $iterationDAO->contact_id
;
828 // special case for calculated field
830 elseif ($field == 'source_contact_id') {
831 $row[$field] = $iterationDAO->contact_id
;
833 elseif ($field == 'pledge_balance_amount') {
834 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
835 // special case for calculated field
837 elseif ($field == 'pledge_next_pay_amount') {
838 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
840 elseif (array_key_exists($field, $contactRelationshipTypes)) {
841 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
842 $relationQuery[$field]->convertToPseudoNames($relDAO);
843 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
845 elseif (isset($fieldValue) &&
848 //check for custom data
849 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
850 $row[$field] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
853 elseif (in_array($field, array(
858 //special case for greeting replacement
859 $fldValue = "{$field}_display";
860 $row[$field] = $iterationDAO->$fldValue;
863 //normal fields with a touch of CRM-3157
867 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
870 case 'state_province':
871 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
875 case 'preferred_communication_method':
876 case 'preferred_mail_format':
877 case 'communication_style':
878 $row[$field] = $i18n->crm_translate($fieldValue);
882 if (isset($metadata[$field])) {
883 // No I don't know why we do it this way & whether we could
884 // make better use of pseudoConstants.
885 if (!empty($metadata[$field]['context'])) {
886 $row[$field] = $i18n->crm_translate($fieldValue, $metadata[$field]);
889 if (!empty($metadata[$field]['pseudoconstant'])) {
890 // This is not our normal syntax for pseudoconstants but I am a bit loath to
891 // call an external function until sure it is not increasing php processing given this
892 // may be iterated 100,000 times & we already have the $imProvider var loaded.
893 // That can be next refactor...
894 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
895 // but I have to reach a stable point....
896 $varName = $metadata[$field]['pseudoconstant']['var'];
898 $row[$field] = $labels[$fieldValue];
903 $row[$field] = $fieldValue;
908 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
909 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
910 $payFieldMapper = array(
911 'componentPaymentField_total_amount' => 'total_amount',
912 'componentPaymentField_contribution_status' => 'contribution_status',
913 'componentPaymentField_payment_instrument' => 'pay_instru',
914 'componentPaymentField_transaction_id' => 'trxn_id',
915 'componentPaymentField_received_date' => 'receive_date',
917 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
920 // if field is empty or null
925 // add payment headers if required
926 if ($addPaymentHeader && $paymentFields) {
927 // @todo rather than do this for every single row do it before the loop starts.
928 // where other header definitions take place.
929 $headerRows = array_merge($headerRows, $paymentHeaders);
930 foreach (array_keys($paymentHeaders) as $paymentHdr) {
931 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
936 $exportTempTable = self
::createTempTable($sqlColumns);
939 //build header only once
942 // If specific payment fields have been selected for export, payment
943 // data will already be in $row. Otherwise, add payment related
944 // information, if appropriate.
945 if ($addPaymentHeader) {
946 if (!$selectedPaymentFields) {
947 if ($paymentFields) {
948 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
949 if (!is_array($paymentData) ||
empty($paymentData)) {
950 $paymentData = $nullContributionDetails;
952 $row = array_merge($row, $paymentData);
954 elseif (!empty($paymentDetails)) {
955 $row = array_merge($row, $nullContributionDetails);
959 //remove organization name for individuals if it is set for current employer
960 if (!empty($row['contact_type']) &&
961 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
963 $row['organization_name'] = '';
966 // add component info
967 // write the row to a file
968 $componentDetails[] = $row;
970 // output every $tempRowCount rows
971 if ($count %
$tempRowCount == 0) {
972 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
973 $componentDetails = array();
976 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
977 $limitReached = TRUE;
979 $offset +
= $rowCount;
982 if ($exportTempTable) {
983 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
985 // if postalMailing option is checked, exclude contacts who are deceased, have
986 // "Do not mail" privacy setting, or have no street address
987 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
988 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
990 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
993 // do merge same address and merge same household processing
994 if ($mergeSameAddress) {
995 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
998 // merge the records if they have corresponding households
999 if ($mergeSameHousehold) {
1000 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1001 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1005 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1007 // In order to be able to write a unit test against this function we need to suppress
1008 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
1009 if (empty($exportParams['suppress_csv_for_testing'])) {
1010 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1013 // return tableName and sqlColumns in test context
1014 return array($exportTempTable, $sqlColumns);
1017 // delete the export temp table and component table
1018 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1019 CRM_Core_DAO
::executeQuery($sql);
1020 CRM_Core_DAO
::reenableFullGroupByMode();
1021 CRM_Utils_System
::civiExit();
1024 CRM_Core_DAO
::reenableFullGroupByMode();
1025 throw new CRM_Core_Exception(ts('No records to export'));
1030 * Name of the export file based on mode.
1032 * @param string $output
1040 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1042 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1043 return ts('CiviCRM Contact Search');
1045 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1046 return ts('CiviCRM Contribution Search');
1048 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1049 return ts('CiviCRM Member Search');
1051 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1052 return ts('CiviCRM Participant Search');
1054 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1055 return ts('CiviCRM Pledge Search');
1057 case CRM_Export_Form_Select
::CASE_EXPORT
:
1058 return ts('CiviCRM Case Search');
1060 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1061 return ts('CiviCRM Grant Search');
1063 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1064 return ts('CiviCRM Activity Search');
1069 * Handle import error file creation.
1071 public static function invoke() {
1072 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
1073 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
1074 if (empty($parserName) ||
empty($type)) {
1078 // clean and ensure parserName is a valid string
1079 $parserName = CRM_Utils_String
::munge($parserName);
1080 $parserClass = explode('_', $parserName);
1082 // make sure parserClass is in the CRM namespace and
1083 // at least 3 levels deep
1084 if ($parserClass[0] == 'CRM' &&
1085 count($parserClass) >= 3
1087 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
1088 // ensure the functions exists
1089 if (method_exists($parserName, 'errorFileName') &&
1090 method_exists($parserName, 'saveFileName')
1092 $errorFileName = $parserName::errorFileName($type);
1093 $saveFileName = $parserName::saveFileName($type);
1094 if (!empty($errorFileName) && !empty($saveFileName)) {
1095 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
1096 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
1097 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
1098 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1099 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1101 readfile($errorFileName);
1105 CRM_Utils_System
::civiExit();
1109 * @param $customSearchClass
1110 * @param $formValues
1113 public static function exportCustom($customSearchClass, $formValues, $order) {
1114 $ext = CRM_Extension_System
::singleton()->getMapper();
1115 if (!$ext->isExtensionClass($customSearchClass)) {
1116 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1119 require_once $ext->classToPath($customSearchClass);
1121 $search = new $customSearchClass($formValues);
1123 $includeContactIDs = FALSE;
1124 if ($formValues['radio_ts'] == 'ts_sel') {
1125 $includeContactIDs = TRUE;
1128 $sql = $search->all(0, 0, $order, $includeContactIDs);
1130 $columns = $search->columns();
1132 $header = array_keys($columns);
1133 $fields = array_values($columns);
1136 $dao = CRM_Core_DAO
::executeQuery($sql);
1138 if (method_exists($search, 'alterRow')) {
1141 while ($dao->fetch()) {
1144 foreach ($fields as $field) {
1145 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
1146 $row[$field] = $dao->$unqualified_field;
1149 $search->alterRow($row);
1154 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1155 CRM_Utils_System
::civiExit();
1160 * @param $sqlColumns
1163 public static function sqlColumnDefn($query, &$sqlColumns, $field) {
1164 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1168 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1169 if ($fieldName == 'id') {
1170 $fieldName = 'civicrm_primary_id';
1173 // early exit for master_id, CRM-12100
1174 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1175 // also for current_employer, CRM-16939
1176 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1177 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1181 if (substr($fieldName, -11) == 'campaign_id') {
1183 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1187 $lookUp = array('prefix_id', 'suffix_id');
1188 // set the sql columns
1189 if (isset($query->_fields
[$field]['type'])) {
1190 switch ($query->_fields
[$field]['type']) {
1191 case CRM_Utils_Type
::T_INT
:
1192 case CRM_Utils_Type
::T_BOOLEAN
:
1193 if (in_array($field, $lookUp)) {
1194 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1197 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1201 case CRM_Utils_Type
::T_STRING
:
1202 if (isset($query->_fields
[$field]['maxlength'])) {
1203 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1206 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1210 case CRM_Utils_Type
::T_TEXT
:
1211 case CRM_Utils_Type
::T_LONGTEXT
:
1212 case CRM_Utils_Type
::T_BLOB
:
1213 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1214 $sqlColumns[$fieldName] = "$fieldName longtext";
1217 case CRM_Utils_Type
::T_FLOAT
:
1218 case CRM_Utils_Type
::T_ENUM
:
1219 case CRM_Utils_Type
::T_DATE
:
1220 case CRM_Utils_Type
::T_TIME
:
1221 case CRM_Utils_Type
::T_TIMESTAMP
:
1222 case CRM_Utils_Type
::T_MONEY
:
1223 case CRM_Utils_Type
::T_EMAIL
:
1224 case CRM_Utils_Type
::T_URL
:
1225 case CRM_Utils_Type
::T_CCNUM
:
1227 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1232 if (substr($fieldName, -3, 3) == '_id') {
1233 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1235 elseif (substr($fieldName, -5, 5) == '_note') {
1236 $sqlColumns[$fieldName] = "$fieldName text";
1239 $changeFields = array(
1245 if (in_array($fieldName, $changeFields)) {
1246 $sqlColumns[$fieldName] = "$fieldName text";
1249 // set the sql columns for custom data
1250 if (isset($query->_fields
[$field]['data_type'])) {
1252 switch ($query->_fields
[$field]['data_type']) {
1254 // May be option labels, which could be up to 512 characters
1255 $length = max(512, CRM_Utils_Array
::value('text_length', $query->_fields
[$field]));
1256 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1260 case 'StateProvince':
1262 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1266 $sqlColumns[$fieldName] = "$fieldName text";
1270 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1275 $sqlColumns[$fieldName] = "$fieldName text";
1283 * @param string $tableName
1285 * @param $sqlColumns
1287 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1288 if (empty($details)) {
1297 $id = CRM_Core_DAO
::singleValueQuery($sql);
1302 $sqlClause = array();
1304 foreach ($details as $dontCare => $row) {
1306 $valueString = array($id);
1307 foreach ($row as $dontCare => $value) {
1308 if (empty($value)) {
1309 $valueString[] = "''";
1312 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1315 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1318 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1320 $sqlValueString = implode(",\n", $sqlClause);
1323 INSERT INTO $tableName $sqlColumnString
1324 VALUES $sqlValueString
1326 CRM_Core_DAO
::executeQuery($sql);
1330 * @param $sqlColumns
1334 public static function createTempTable(&$sqlColumns) {
1335 //creating a temporary table for the search result that need be exported
1336 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1338 // also create the sql table
1339 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1340 CRM_Core_DAO
::executeQuery($sql);
1343 CREATE TABLE {$exportTempTable} (
1344 id int unsigned NOT NULL AUTO_INCREMENT,
1346 $sql .= implode(",\n", array_values($sqlColumns));
1351 // add indexes for street_address and household_name if present
1352 $addIndices = array(
1355 'civicrm_primary_id',
1358 foreach ($addIndices as $index) {
1359 if (isset($sqlColumns[$index])) {
1361 INDEX index_{$index}( $index )
1367 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1370 CRM_Core_DAO
::executeQuery($sql);
1371 return $exportTempTable;
1375 * @param string $tableName
1376 * @param $headerRows
1377 * @param $sqlColumns
1378 * @param array $exportParams
1380 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1381 // check if any records are present based on if they have used shared address feature,
1382 // and not based on if city / state .. matches.
1384 SELECT r1.id as copy_id,
1385 r1.civicrm_primary_id as copy_contact_id,
1386 r1.addressee as copy_addressee,
1387 r1.addressee_id as copy_addressee_id,
1388 r1.postal_greeting as copy_postal_greeting,
1389 r1.postal_greeting_id as copy_postal_greeting_id,
1391 r2.civicrm_primary_id as master_contact_id,
1392 r2.postal_greeting as master_postal_greeting,
1393 r2.postal_greeting_id as master_postal_greeting_id,
1394 r2.addressee as master_addressee,
1395 r2.addressee_id as master_addressee_id
1397 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1398 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1400 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1402 // find all the records that have the same street address BUT not in a household
1403 // require match on city and state as well
1405 SELECT r1.id as master_id,
1406 r1.civicrm_primary_id as master_contact_id,
1407 r1.postal_greeting as master_postal_greeting,
1408 r1.postal_greeting_id as master_postal_greeting_id,
1409 r1.addressee as master_addressee,
1410 r1.addressee_id as master_addressee_id,
1412 r2.civicrm_primary_id as copy_contact_id,
1413 r2.postal_greeting as copy_postal_greeting,
1414 r2.postal_greeting_id as copy_postal_greeting_id,
1415 r2.addressee as copy_addressee,
1416 r2.addressee_id as copy_addressee_id
1418 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1419 r1.city = r2.city AND
1420 r1.state_province_id = r2.state_province_id )
1421 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1422 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1423 AND ( r1.street_address != '' )
1427 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1429 // unset ids from $merge already present in $linkedMerge
1430 foreach ($linkedMerge as $masterID => $values) {
1431 $keys = array($masterID);
1432 $keys = array_merge($keys, array_keys($values['copy']));
1433 foreach ($merge as $mid => $vals) {
1434 if (in_array($mid, $keys)) {
1435 unset($merge[$mid]);
1438 foreach ($values['copy'] as $copyId) {
1439 if (in_array($copyId, $keys)) {
1440 unset($merge[$mid]['copy'][$copyId]);
1446 $merge = $merge +
$linkedMerge;
1448 foreach ($merge as $masterID => $values) {
1451 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1455 1 => array($values['addressee'], 'String'),
1456 2 => array($values['postalGreeting'], 'String'),
1457 3 => array($values['emailGreeting'], 'String'),
1458 4 => array($masterID, 'Integer'),
1460 CRM_Core_DAO
::executeQuery($sql, $params);
1462 // delete all copies
1463 $deleteIDs = array_keys($values['copy']);
1464 $deleteIDString = implode(',', $deleteIDs);
1466 DELETE FROM $tableName
1467 WHERE id IN ( $deleteIDString )
1469 CRM_Core_DAO
::executeQuery($sql);
1472 // unset temporary columns that were added for postal mailing format
1473 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1474 $unsetKeys = array_keys($sqlColumns);
1475 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1476 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1477 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1484 * @param int $contactId
1485 * @param array $exportParams
1489 public static function _replaceMergeTokens($contactId, $exportParams) {
1490 $greetings = array();
1493 $greetingFields = array(
1497 foreach ($greetingFields as $greeting) {
1498 if (!empty($exportParams[$greeting])) {
1499 $greetingLabel = $exportParams[$greeting];
1500 if (empty($contact)) {
1505 $contact = civicrm_api('contact', 'get', $values);
1507 if (!empty($contact['is_error'])) {
1510 $contact = $contact['values'][$contact['id']];
1513 $tokens = array('contact' => $greetingLabel);
1514 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1521 * The function unsets static part of the string, if token is the dynamic part.
1523 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1524 * i.e 'Hello Alan' => converted to => 'Alan'
1526 * @param string $parsedString
1527 * @param string $defaultGreeting
1528 * @param bool $addressMergeGreetings
1529 * @param string $greetingType
1533 public static function _trimNonTokens(
1534 &$parsedString, $defaultGreeting,
1535 $addressMergeGreetings, $greetingType = 'postal_greeting'
1537 if (!empty($addressMergeGreetings[$greetingType])) {
1538 $greetingLabel = $addressMergeGreetings[$greetingType];
1540 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1542 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1543 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1544 foreach ($stringsToBeReplaced as $key => $string) {
1545 // to keep one space
1546 $stringsToBeReplaced[$key] = ltrim($string);
1548 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1550 return $parsedString;
1555 * @param array $exportParams
1556 * @param bool $sharedAddress
1560 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1561 static $contactGreetingTokens = array();
1563 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1564 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1566 $merge = $parents = array();
1567 $dao = CRM_Core_DAO
::executeQuery($sql);
1569 while ($dao->fetch()) {
1570 $masterID = $dao->master_id
;
1571 $copyID = $dao->copy_id
;
1572 $masterPostalGreeting = $dao->master_postal_greeting
;
1573 $masterAddressee = $dao->master_addressee
;
1574 $copyAddressee = $dao->copy_addressee
;
1576 if (!$sharedAddress) {
1577 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1578 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1580 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1581 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1583 $masterAddressee = CRM_Utils_Array
::value('addressee',
1584 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1587 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1588 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1590 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1591 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1593 $copyAddressee = CRM_Utils_Array
::value('addressee',
1594 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1598 if (!isset($merge[$masterID])) {
1599 // check if this is an intermediate child
1600 // this happens if there are 3 or more matches a,b, c
1601 // the above query will return a, b / a, c / b, c
1602 // we might be doing a bit more work, but for now its ok, unless someone
1603 // knows how to fix the query above
1604 if (isset($parents[$masterID])) {
1605 $masterID = $parents[$masterID];
1608 $merge[$masterID] = array(
1609 'addressee' => $masterAddressee,
1611 'postalGreeting' => $masterPostalGreeting,
1613 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1616 $parents[$copyID] = $masterID;
1618 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1620 if (!empty($exportParams['postal_greeting_other']) &&
1621 count($merge[$masterID]['copy']) >= 1
1623 // use static greetings specified if no of contacts > 2
1624 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1626 elseif ($copyPostalGreeting) {
1627 self
::_trimNonTokens($copyPostalGreeting,
1628 $postalOptions[$dao->copy_postal_greeting_id
],
1631 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1632 // if there happens to be a duplicate, remove it
1633 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1636 if (!empty($exportParams['addressee_other']) &&
1637 count($merge[$masterID]['copy']) >= 1
1639 // use static greetings specified if no of contacts > 2
1640 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1642 elseif ($copyAddressee) {
1643 self
::_trimNonTokens($copyAddressee,
1644 $addresseeOptions[$dao->copy_addressee_id
],
1645 $exportParams, 'addressee'
1647 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1650 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1657 * Merge household record into the individual record
1660 * @param string $exportTempTable
1661 * Temporary temp table that stores the records.
1662 * @param array $headerRows
1663 * Array of headers for the export file.
1664 * @param array $sqlColumns
1665 * Array of names of the table columns of the temp table.
1666 * @param string $prefix
1667 * Name of the relationship type that is prefixed to the table columns.
1669 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1670 $prefixColumn = $prefix . '_';
1671 $allKeys = array_keys($sqlColumns);
1672 $replaced = array();
1673 $headerRows = array_values($headerRows);
1675 // name map of the non standard fields in header rows & sql columns
1676 $mappingFields = array(
1677 'civicrm_primary_id' => 'id',
1678 'contact_source' => 'source',
1679 'current_employer_id' => 'employer_id',
1680 'contact_is_deleted' => 'is_deleted',
1681 'name' => 'address_name',
1682 'provider_id' => 'im_service_provider',
1683 'phone_type_id' => 'phone_type',
1686 //figure out which columns are to be replaced by which ones
1687 foreach ($sqlColumns as $columnNames => $dontCare) {
1688 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1689 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1692 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1694 if (!empty($sqlColumns[$householdColName])) {
1695 $replaced[$columnNames] = $householdColName;
1699 $query = "UPDATE $exportTempTable SET ";
1702 foreach ($replaced as $from => $to) {
1703 $clause[] = "$from = $to ";
1704 unset($sqlColumns[$to]);
1705 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1706 unset($headerRows[$key]);
1709 $query .= implode(",\n", $clause);
1710 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1712 CRM_Core_DAO
::executeQuery($query);
1714 //drop the table columns that store redundant household info
1715 $dropQuery = "ALTER TABLE $exportTempTable ";
1716 foreach ($replaced as $householdColumns) {
1717 $dropClause[] = " DROP $householdColumns ";
1719 $dropQuery .= implode(",\n", $dropClause);
1721 CRM_Core_DAO
::executeQuery($dropQuery);
1723 // also drop the temp table if exists
1724 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1725 CRM_Core_DAO
::executeQuery($sql);
1727 // clean up duplicate records
1729 CREATE TABLE {$exportTempTable}_temp SELECT *
1730 FROM {$exportTempTable}
1731 GROUP BY civicrm_primary_id ";
1733 CRM_Core_DAO
::executeQuery($query);
1735 $query = "DROP TABLE $exportTempTable";
1736 CRM_Core_DAO
::executeQuery($query);
1738 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1739 CRM_Core_DAO
::executeQuery($query);
1743 * @param $exportTempTable
1744 * @param $headerRows
1745 * @param $sqlColumns
1746 * @param $exportMode
1747 * @param null $saveFile
1748 * @param string $batchItems
1750 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1751 $writeHeader = TRUE;
1753 $limit = self
::EXPORT_ROW_COUNT
;
1755 $query = "SELECT * FROM $exportTempTable";
1758 $limitQuery = $query . "
1759 LIMIT $offset, $limit
1761 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1767 $componentDetails = array();
1768 while ($dao->fetch()) {
1771 foreach ($sqlColumns as $column => $dontCare) {
1772 $row[$column] = $dao->$column;
1774 $componentDetails[] = $row;
1776 if ($exportMode == 'financial') {
1777 $getExportFileName = 'CiviCRM Contribution Search';
1780 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1782 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1789 if ($saveFile && !empty($csvRows)) {
1790 $batchItems .= $csvRows;
1793 $writeHeader = FALSE;
1799 * Manipulate header rows for relationship fields.
1801 * @param $headerRows
1802 * @param $contactRelationshipTypes
1804 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1805 foreach ($headerRows as & $header) {
1806 $split = explode('-', $header);
1807 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1808 $split[0] = $relationTypeName;
1809 $header = implode('-', $split);
1815 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1816 * or have no street address
1817 * @param $exportTempTable
1818 * @param $headerRows
1819 * @param $sqlColumns
1820 * @param $exportParams
1822 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1823 $whereClause = array();
1825 if (array_key_exists('is_deceased', $sqlColumns)) {
1826 $whereClause[] = 'is_deceased = 1';
1829 if (array_key_exists('do_not_mail', $sqlColumns)) {
1830 $whereClause[] = 'do_not_mail = 1';
1833 if (array_key_exists('street_address', $sqlColumns)) {
1834 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1836 // check for supplemental_address_1
1837 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1838 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1839 'address_options', TRUE, NULL, TRUE
1841 if (!empty($addressOptions['supplemental_address_1'])) {
1842 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1843 // enclose it again, since we are doing an AND in between a set of ORs
1844 $addressWhereClause = "( $addressWhereClause )";
1848 $whereClause[] = $addressWhereClause;
1851 if (!empty($whereClause)) {
1852 $whereClause = implode(' OR ', $whereClause);
1855 FROM $exportTempTable
1856 WHERE {$whereClause}";
1857 CRM_Core_DAO
::singleValueQuery($query);
1860 // unset temporary columns that were added for postal mailing format
1861 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1862 $unsetKeys = array_keys($sqlColumns);
1863 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1864 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1865 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1872 * Build componentPayment fields.
1874 public static function componentPaymentFields() {
1875 static $componentPaymentFields;
1876 if (!isset($componentPaymentFields)) {
1877 $componentPaymentFields = array(
1878 'componentPaymentField_total_amount' => ts('Total Amount'),
1879 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1880 'componentPaymentField_received_date' => ts('Date Received'),
1881 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1882 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1885 return $componentPaymentFields;
1889 * Set the definition for the header rows and sql columns based on the field to output.
1891 * @param string $field
1892 * @param array $headerRows
1893 * @param array $sqlColumns
1894 * Columns to go in the temp table.
1895 * @param CRM_Contact_BAO_Query $query
1896 * @param array|string $value
1897 * @param array $phoneTypes
1898 * @param array $imProviders
1899 * @param array $contactRelationshipTypes
1900 * @param string $relationQuery
1901 * @param array $selectedPaymentFields
1904 public static function setHeaderRows($field, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
1906 // Split campaign into 2 fields for id and title
1907 if (substr($field, -14) == 'campaign_title') {
1908 $headerRows[] = ts('Campaign Title');
1910 elseif (substr($field, -11) == 'campaign_id') {
1911 $headerRows[] = ts('Campaign ID');
1913 elseif (isset($query->_fields
[$field]['title'])) {
1914 $headerRows[] = $query->_fields
[$field]['title'];
1916 elseif ($field == 'phone_type_id') {
1917 $headerRows[] = ts('Phone Type');
1919 elseif ($field == 'provider_id') {
1920 $headerRows[] = ts('IM Service Provider');
1922 elseif (substr($field, 0, 5) == 'case_' && $query->_fields
['case'][$field]['title']) {
1923 $headerRows[] = $query->_fields
['case'][$field]['title'];
1925 elseif (array_key_exists($field, $contactRelationshipTypes)) {
1926 foreach ($value as $relationField => $relationValue) {
1927 // below block is same as primary block (duplicate)
1928 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
1929 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
1930 $headerName = $field . '-' . $relationField;
1933 if ($relationField == 'current_employer') {
1934 $headerName = $field . '-' . 'current_employer';
1937 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
1941 $headerRows[] = $headerName;
1943 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1945 elseif ($relationField == 'phone_type_id') {
1946 $headerName = $field . '-' . 'Phone Type';
1947 $headerRows[] = $headerName;
1948 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1950 elseif ($relationField == 'provider_id') {
1951 $headerName = $field . '-' . 'Im Service Provider';
1952 $headerRows[] = $headerName;
1953 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1955 elseif ($relationField == 'state_province_id') {
1956 $headerName = $field . '-' . 'state_province_id';
1957 $headerRows[] = $headerName;
1958 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1960 elseif (is_array($relationValue) && $relationField == 'location') {
1961 // fix header for location type case
1962 foreach ($relationValue as $ltype => $val) {
1963 foreach (array_keys($val) as $fld) {
1964 $type = explode('-', $fld);
1966 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
1968 if (!empty($type[1])) {
1969 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1970 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1972 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1973 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1976 $headerName = $field . '-' . $hdr;
1977 $headerRows[] = $headerName;
1978 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
1983 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1985 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1986 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1989 $headerRows[] = $field;
1992 self
::sqlColumnDefn($query, $sqlColumns, $field);
1994 return array($headerRows, $sqlColumns);
1998 * Get the various arrays that we use to structure our output.
2000 * The extraction of these has been moved to a separate function for clarity and so that
2001 * tests can be added - in particular on the $outputHeaders array.
2003 * However it still feels a bit like something that I'm too polite to write down and this should be seen
2004 * as a step on the refactoring path rather than how it should be.
2006 * @param array $returnProperties
2007 * @param CRM_Contact_BAO_Contact $query
2008 * @param array $contactRelationshipTypes
2009 * @param string $relationQuery
2010 * @param array $selectedPaymentFields
2012 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
2013 * alias for the field generated by BAO_Query object.
2014 * - headerRows Array of the column header strings to put in the csv header - non-associative.
2015 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
2016 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
2017 * I'm too embarassed to discuss here.
2019 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
2020 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
2021 * in the main DAO loop is done once per row & that coule be 100,000 times.)
2022 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
2023 * - a) the function used is more efficient or
2024 * - b) this code is old & outdated. Submit your answers to circular bin or better
2025 * yet find a way to comment them for posterity.
2027 public static function getExportStructureArrays($returnProperties, $query, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields) {
2028 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
2029 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
2030 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
2032 foreach ($returnProperties as $key => $value) {
2033 if ($key != 'location' ||
!is_array($value)) {
2034 $outputColumns[$key] = $value;
2035 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2038 foreach ($value as $locationType => $locationFields) {
2039 foreach (array_keys($locationFields) as $locationFieldName) {
2040 $type = explode('-', $locationFieldName);
2042 $actualDBFieldName = $type[0];
2043 $outputFieldName = $locationType . '-' . $query->_fields
[$actualDBFieldName]['title'];
2044 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
2046 if (!empty($type[1])) {
2047 $daoFieldName .= "-" . $type[1];
2048 if ($actualDBFieldName == 'phone') {
2049 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
2051 elseif ($actualDBFieldName == 'im') {
2052 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
2055 if ($type[0] == 'im_provider') {
2056 // Warning: shame inducing hack.
2057 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
2059 self
::sqlColumnDefn($query, $sqlColumns, $outputFieldName);
2060 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $query, $value, $phoneTypes, $imProviders, $contactRelationshipTypes, $relationQuery, $selectedPaymentFields);
2061 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
2062 $metadata[$daoFieldName] = array('context' => 'country');
2064 if ($actualDBFieldName == 'state_province') {
2065 $metadata[$daoFieldName] = array('context' => 'province');
2067 $outputColumns[$daoFieldName] = TRUE;
2072 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
2076 * Get the values of linked household contact.
2078 * @param CRM_Core_DAO $relDAO
2079 * @param array $value
2080 * @param string $field
2083 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
2084 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
2085 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
2086 $i18n = CRM_Core_I18n
::singleton();
2087 foreach ($value as $relationField => $relationValue) {
2088 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
2089 $fieldValue = $relDAO->$relationField;
2090 if ($relationField == 'phone_type_id') {
2091 $fieldValue = $phoneTypes[$relationValue];
2093 elseif ($relationField == 'provider_id') {
2094 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
2097 elseif (is_object($relDAO) && in_array($relationField, array(
2103 //special case for greeting replacement
2104 $fldValue = "{$relationField}_display";
2105 $fieldValue = $relDAO->$fldValue;
2108 elseif (is_object($relDAO) && $relationField == 'state_province') {
2109 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
2111 elseif (is_object($relDAO) && $relationField == 'country') {
2112 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
2117 $field = $field . '_';
2118 $relPrefix = $field . $relationField;
2120 if (is_object($relDAO) && $relationField == 'id') {
2121 $row[$relPrefix] = $relDAO->contact_id
;
2123 elseif (is_array($relationValue) && $relationField == 'location') {
2124 foreach ($relationValue as $ltype => $val) {
2125 foreach (array_keys($val) as $fld) {
2126 $type = explode('-', $fld);
2127 $fldValue = "{$ltype}-" . $type[0];
2128 if (!empty($type[1])) {
2129 $fldValue .= "-" . $type[1];
2131 // CRM-3157: localise country, region (both have ‘country’ context)
2132 // and state_province (‘province’ context)
2134 case (!is_object($relDAO)):
2135 $row[$field . '_' . $fldValue] = '';
2138 case in_array('country', $type):
2139 case in_array('world_region', $type):
2140 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2141 array('context' => 'country')
2145 case in_array('state_province', $type):
2146 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
2147 array('context' => 'province')
2152 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
2158 elseif (isset($fieldValue) && $fieldValue != '') {
2159 //check for custom data
2160 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
2161 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
2164 //normal relationship fields
2165 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
2166 switch ($relationField) {
2168 case 'world_region':
2169 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
2172 case 'state_province':
2173 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
2177 $row[$relPrefix] = $fieldValue;
2183 // if relation field is empty or null
2184 $row[$relPrefix] = '';