3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
37 * This class contains the funtions for Component export
40 class CRM_Export_BAO_Export
{
41 // increase this number a lot to avoid making too many queries
42 // LIMIT is not much faster than a no LIMIT query
44 CONST EXPORT_ROW_COUNT
= 10000;
47 * Function to get the list the export fields
49 * @param int $selectAll user preference while export
50 * @param array $ids contact ids
51 * @param array $params associated array of fields
52 * @param string $order order by clause
53 * @param array $fields associated array of fields
54 * @param array $moreReturnProperties additional return fields
55 * @param int $exportMode export mode
56 * @param string $componentClause component clause
57 * @param string $componentTable component table
58 * @param bool $mergeSameAddress merge records if they have same address
59 * @param bool $mergeSameHousehold merge records if they belong to the same household
64 static function exportComponents($selectAll,
69 $moreReturnProperties = NULL,
70 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
71 $componentClause = NULL,
72 $componentTable = NULL,
73 $mergeSameAddress = FALSE,
74 $mergeSameHousehold = FALSE,
75 $exportParams = array(),
76 $queryOperator = 'AND'
78 $headerRows = $returnProperties = array();
79 $primary = $paymentFields = $selectedPaymentFields = FALSE;
80 $origFields = $fields;
81 $queryMode = $relationField = NULL;
83 $allCampaigns = array();
85 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
86 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
87 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
96 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
98 switch ($exportMode) {
99 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
100 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
103 case CRM_Export_Form_Select
::EVENT_EXPORT
:
104 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
107 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
108 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
111 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
112 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
115 case CRM_Export_Form_Select
::CASE_EXPORT
:
116 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
119 case CRM_Export_Form_Select
::GRANT_EXPORT
:
120 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
123 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
124 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
128 //construct return properties
129 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
130 $locationTypeFields = array(
132 'supplemental_address_1',
133 'supplemental_address_2',
136 'postal_code_suffix',
146 foreach ($fields as $key => $value) {
147 $phoneTypeId = $imProviderId = NULL;
148 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
152 // get phoneType id and IM service provider id seperately
153 if ($fieldName == 'phone') {
154 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
156 elseif ($fieldName == 'im') {
157 $imProviderId = CRM_Utils_Array
::value(3, $value);
160 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
161 if (CRM_Utils_Array
::value(2, $value)) {
162 $relationField = CRM_Utils_Array
::value(2, $value);
163 if (trim(CRM_Utils_Array
::value(3, $value))) {
164 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
167 $relLocTypeId = 'Primary';
170 if ($relationField == 'phone') {
171 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
173 elseif ($relationField == 'im') {
174 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
177 elseif (CRM_Utils_Array
::value(4, $value)) {
178 $relationField = CRM_Utils_Array
::value(4, $value);
179 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
180 if ($relationField == 'phone') {
181 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
183 elseif ($relationField == 'im') {
184 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
189 $contactType = CRM_Utils_Array
::value(0, $value);
190 $locTypeId = CRM_Utils_Array
::value(2, $value);
192 if ($relationField) {
193 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
194 if ($relPhoneTypeId) {
195 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
197 elseif ($relIMProviderId) {
198 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
201 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
203 $relPhoneTypeId = $relIMProviderId = NULL;
206 $returnProperties[$relationshipTypes][$relationField] = 1;
209 elseif (is_numeric($locTypeId)) {
211 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
213 elseif ($imProviderId) {
214 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
217 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
221 //hack to fix component fields
222 if ($fieldName == 'event_id') {
223 $returnProperties['event_title'] = 1;
226 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
227 array_key_exists( $fieldName, self
::componentPaymentFields())
229 $selectedPaymentFields = true;
230 $paymentTableId = 'participant_id';
231 $returnProperties[$fieldName] = 1;
234 $returnProperties[$fieldName] = 1;
239 // hack to add default returnproperty based on export mode
240 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
241 $returnProperties['contribution_id'] = 1;
243 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
244 $returnProperties['participant_id'] = 1;
245 if (CRM_Utils_Array
::value('participant_role', $returnProperties)) {
246 unset($returnProperties['participant_role']);
247 $returnProperties['participant_role_id'] = 1;
250 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
251 $returnProperties['membership_id'] = 1;
253 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
254 $returnProperties['pledge_id'] = 1;
256 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
257 $returnProperties['case_id'] = 1;
259 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
260 $returnProperties['grant_id'] = 1;
262 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
263 $returnProperties['activity_id'] = 1;
268 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
269 foreach ($fields as $key => $var) {
270 if ($key && (substr($key, 0, 6) != 'custom')) {
272 $returnProperties[$key] = 1;
277 $returnProperties['location_type'] = 1;
278 $returnProperties['im_provider'] = 1;
279 $returnProperties['phone_type_id'] = 1;
280 $returnProperties['provider_id'] = 1;
281 $returnProperties['current_employer'] = 1;
284 $extraReturnProperties = array();
285 $paymentFields = FALSE;
287 switch ($queryMode) {
288 case CRM_Contact_BAO_Query
::MODE_EVENT
:
289 $paymentFields = TRUE;
290 $paymentTableId = 'participant_id';
293 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
294 $paymentFields = TRUE;
295 $paymentTableId = 'membership_id';
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);
309 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
310 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
311 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
313 if (!empty($extraReturnProperties)) {
314 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
317 // unset non exportable fields for components
318 $nonExpoFields = array(
319 'groups', 'tags', 'notes', 'contribution_status_id',
320 'pledge_status_id', 'pledge_payment_status_id',
322 foreach ($nonExpoFields as $value) {
323 unset($returnProperties[$value]);
328 if ($mergeSameAddress) {
329 //make sure the addressee fields are selected
330 //while using merge same address feature
331 $returnProperties['addressee'] = 1;
332 $returnProperties['postal_greeting'] = 1;
333 $returnProperties['email_greeting'] = 1;
334 $returnProperties['street_name'] = 1;
335 $returnProperties['household_name'] = 1;
336 $returnProperties['street_address'] = 1;
337 $returnProperties['city'] = 1;
338 $returnProperties['state_province'] = 1;
340 // some columns are required for assistance incase they are not already present
341 $exportParams['merge_same_address']['temp_columns'] = array();
342 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
343 foreach ($tempColumns as $column) {
344 if (!array_key_exists($column, $returnProperties)) {
345 $returnProperties[$column] = 1;
346 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
347 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
352 if (!$selectAll && $componentTable && CRM_Utils_Array
::value('additional_group', $exportParams)) {
353 // If an Additional Group is selected, then all contacts in that group are
354 // added to the export set (filtering out duplicates).
356 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";
357 CRM_Core_DAO
::executeQuery($query);
360 if ($moreReturnProperties) {
362 if (CRM_Utils_Array
::value('group', $moreReturnProperties)) {
363 unset($moreReturnProperties['group']);
364 $moreReturnProperties['groups'] = 1;
366 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
369 $exportParams['postal_mailing_export']['temp_columns'] = array();
370 if ($exportParams['exportOption'] == 2 &&
371 isset($exportParams['postal_mailing_export']) &&
372 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
374 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
375 foreach ($postalColumns as $column) {
376 if (!array_key_exists($column, $returnProperties)) {
377 $returnProperties[$column] = 1;
378 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
383 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
384 FALSE, FALSE, $queryMode,
385 FALSE, TRUE, TRUE, NULL, $queryOperator
388 list($select, $from, $where, $having) = $query->query();
390 if ($mergeSameHousehold == 1) {
391 if (!$returnProperties['id']) {
392 $returnProperties['id'] = 1;
395 //also merge Head of Household
396 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
397 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
399 foreach ($returnProperties as $key => $value) {
400 if (!array_key_exists($key, $contactRelationshipTypes)) {
401 $returnProperties[$relationKeyMOH][$key] = $value;
402 $returnProperties[$relationKeyHOH][$key] = $value;
406 unset($returnProperties[$relationKeyMOH]['location_type']);
407 unset($returnProperties[$relationKeyMOH]['im_provider']);
408 unset($returnProperties[$relationKeyHOH]['location_type']);
409 unset($returnProperties[$relationKeyHOH]['im_provider']);
412 $allRelContactArray = $relationQuery = array();
414 foreach ($contactRelationshipTypes as $rel => $dnt) {
415 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
416 $allRelContactArray[$rel] = array();
417 // build Query for each relationship
418 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
419 NULL, FALSE, FALSE, $queryMode
421 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
423 list($id, $direction) = explode('_', $rel, 2);
424 // identify the relationship direction
425 $contactA = 'contact_id_a';
426 $contactB = 'contact_id_b';
427 if ($direction == 'b_a') {
428 $contactA = 'contact_id_b';
429 $contactB = 'contact_id_a';
431 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
434 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
435 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
436 $query = "SELECT contact_id FROM civicrm_activity_contact
437 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
438 record_type_id = {$sourceID}";
439 $dao = CRM_Core_DAO
::executeQuery($query);
440 while ($dao->fetch()) {
441 $relIDs[] = $dao->contact_id
;
445 switch ($exportMode) {
446 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
447 $component = 'civicrm_contribution';
450 case CRM_Export_Form_Select
::EVENT_EXPORT
:
451 $component = 'civicrm_participant';
454 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
455 $component = 'civicrm_membership';
458 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
459 $component = 'civicrm_pledge';
462 case CRM_Export_Form_Select
::GRANT_EXPORT
:
463 $component = 'civicrm_grant';
467 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
468 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
471 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
475 $relationshipJoin = $relationshipClause = '';
476 if (!$selectAll && $componentTable) {
477 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
479 elseif (!empty($relIDs)) {
480 $relID = implode(',', $relIDs);
481 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
484 $relationFrom = " {$relationFrom}
485 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
486 {$relationshipJoin} ";
488 //check for active relationship status only
489 $today = date('Ymd');
490 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
491 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
492 $relationGroupBy = " GROUP BY crel.{$contactA}";
493 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
494 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
496 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
497 while ($allRelContactDAO->fetch()) {
498 //FIX Me: Migrate this to table rather than array
499 // build the array of all related contacts
500 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
502 $allRelContactDAO->free();
506 // make sure the groups stuff is included only if specifically specified
507 // by the fields param (CRM-1969), else we limit the contacts outputted to only
508 // ones that are part of a group
509 if (CRM_Utils_Array
::value('groups', $returnProperties)) {
510 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
511 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
512 // total hack for export, CRM-3618
513 $from = str_replace($oldClause,
519 if (!$selectAll && $componentTable) {
520 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
522 elseif ($componentClause) {
524 $where = "WHERE $componentClause";
527 $where .= " AND $componentClause";
531 // CRM-13982 - check if is deleted
532 $excludeTrashed = TRUE;
533 foreach ($params as $value) {
534 if ($value[0] == 'contact_is_deleted') {
535 $excludeTrashed = FALSE;
538 if (empty($where) && $excludeTrashed) {
539 $where = "WHERE contact_a.is_deleted != 1";
541 elseif ($excludeTrashed) {
542 $where .= " AND contact_a.is_deleted != 1";
545 $queryString = "$select $from $where $having";
548 if (CRM_Utils_Array
::value('tags', $returnProperties) ||
549 CRM_Utils_Array
::value('groups', $returnProperties) ||
550 CRM_Utils_Array
::value('notes', $returnProperties) ||
552 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
554 $groupBy = " GROUP BY contact_a.id";
557 switch ($exportMode) {
558 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
559 $groupBy = 'GROUP BY civicrm_contribution.id';
562 case CRM_Export_Form_Select
::EVENT_EXPORT
:
563 $groupBy = 'GROUP BY civicrm_participant.id';
566 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
567 $groupBy = " GROUP BY civicrm_membership.id";
571 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
572 $groupBy = " GROUP BY civicrm_activity.id ";
574 $queryString .= $groupBy;
576 list($field, $dir) = explode(' ', $order, 2);
577 $field = trim($field);
578 if (CRM_Utils_Array
::value($field, $returnProperties)) {
579 // $queryString .= " ORDER BY $order";
583 $multipleSelectFields = array('preferred_communication_method' => 1);
585 $addPaymentHeader = FALSE;
587 $paymentDetails = array();
588 if ($paymentFields ||
$selectedPaymentFields) {
590 // get payment related in for event and members
591 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
592 //get all payment headers.
593 // If we haven't selected specific payment fields, load in all the
595 if (!$selectedPaymentFields) {
596 $paymentHeaders = self
::componentPaymentFields();
597 if (!empty($paymentDetails)) {
598 $addPaymentHeader = TRUE;
601 // If we have seleted specific payment fields, leave the payment headers
602 // as an empty array; the headers for each selected field will be added
605 $paymentHeaders = array();
607 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
610 // Split campaign into 2 fields for id and title
611 $campaignReturnProperties = array();
612 foreach ($returnProperties as $fld => $true) {
613 $campaignReturnProperties[$fld] = $true;
614 if (substr($fld, -11) == 'campaign_id') {
615 $exportCampaign = TRUE;
616 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
619 $returnProperties = $campaignReturnProperties;
621 if (isset($exportCampaign)) {
622 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
625 $componentDetails = $headerRows = $sqlColumns = array();
628 $rowCount = self
::EXPORT_ROW_COUNT
;
630 // we write to temp table often to avoid using too much memory
635 // for CRM-3157 purposes
636 $i18n = CRM_Core_I18n
::singleton();
639 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
640 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
645 while ($dao->fetch()) {
649 //convert the pseudo constants
650 $query->convertToPseudoNames($dao);
652 //first loop through returnproperties so that we return what is required, and in same order.
653 $relationshipField = 0;
654 foreach ($returnProperties as $field => $value) {
655 //we should set header only once
658 // Split campaign into 2 fields for id and title
659 if (substr($field, -8) == 'campaign') {
660 $headerRows[] = ts('Campaign Title');
662 elseif (substr($field, -11) == 'campaign_id') {
663 $headerRows[] = ts('Campaign ID');
665 elseif (isset($query->_fields
[$field]['title'])) {
666 $headerRows[] = $query->_fields
[$field]['title'];
668 elseif ($field == 'phone_type_id') {
669 $headerRows[] = ts('Phone Type');
671 elseif ($field == 'provider_id') {
672 $headerRows[] = ts('IM Service Provider');
674 elseif (is_array($value) && $field == 'location') {
675 // fix header for location type case
676 foreach ($value as $ltype => $val) {
677 foreach (array_keys($val) as $fld) {
678 $type = explode('-', $fld);
679 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
681 if (CRM_Utils_Array
::value(1, $type)) {
682 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
683 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
685 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
686 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
689 $headerRows[] = $hdr;
690 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
695 elseif (substr($field, 0, 5) == 'case_') {
696 if ($query->_fields
['case'][$field]['title']) {
697 $headerRows[] = $query->_fields
['case'][$field]['title'];
699 elseif ($query->_fields
['activity'][$field]['title']) {
700 $headerRows[] = $query->_fields
['activity'][$field]['title'];
703 elseif (array_key_exists($field, $contactRelationshipTypes)) {
705 foreach ($value as $relationField => $relationValue) {
706 // below block is same as primary block (duplicate)
707 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
708 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
709 $headerName = $field . '-' . $relationField;
712 if ($relationField == 'current_employer') {
713 $headerName = $field . '-' . 'current_employer';
716 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
720 $headerRows[] = $headerName;
722 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
724 elseif ($relationField == 'phone_type_id') {
725 $headerName = $field . '-' . 'Phone Type';
726 $headerRows[] = $headerName;
727 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
729 elseif ($relationField == 'provider_id') {
730 $headerName = $field . '-' . 'Im Service Provider';
731 $headerRows[] = $headerName;
732 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
734 elseif ($relationField == 'state_province_id') {
735 $headerName = $field . '-' . 'state_province_id';
736 $headerRows[] = $headerName;
737 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
739 elseif (is_array($relationValue) && $relationField == 'location') {
740 // fix header for location type case
741 foreach ($relationValue as $ltype => $val) {
742 foreach (array_keys($val) as $fld) {
743 $type = explode('-', $fld);
745 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
747 if (CRM_Utils_Array
::value(1, $type)) {
748 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
749 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
751 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
752 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
755 $headerName = $field . '-' . $hdr;
756 $headerRows[] = $headerName;
757 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
763 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
764 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
767 $headerRows[] = $field;
771 self
::sqlColumnDefn($query, $sqlColumns, $field);
775 // add im_provider to $dao object
776 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
777 $dao->im_provider
= $dao->provider_id
;
780 //build row values (data)
782 if (property_exists($dao, $field)) {
783 $fieldValue = $dao->$field;
784 // to get phone type from phone type id
785 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
786 $fieldValue = $phoneTypes[$fieldValue];
788 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
789 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
791 elseif ($field == 'participant_role_id') {
792 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
793 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
794 $viewRoles = array();
795 foreach (explode($sep, $dao->$field) as $k => $v) {
796 $viewRoles[] = $participantRoles[$v];
798 $fieldValue = implode(',', $viewRoles);
800 elseif ($field == 'master_id') {
801 $masterAddressId = NULL;
802 if (isset($dao->master_id
)) {
803 $masterAddressId = $dao->master_id
;
805 // get display name of contact that address is shared.
806 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $dao->contact_id
);
810 if ($field == 'id') {
811 $row[$field] = $dao->contact_id
;
812 // special case for calculated field
814 elseif ($field == 'source_contact_id') {
815 $row[$field] = $dao->contact_id
;
817 elseif ($field == 'pledge_balance_amount') {
818 $row[$field] = $dao->pledge_amount
- $dao->pledge_total_paid
;
819 // special case for calculated field
821 elseif ($field == 'pledge_next_pay_amount') {
822 $row[$field] = $dao->pledge_next_pay_amount +
$dao->pledge_outstanding_amount
;
824 elseif (in_array(substr($field, 0, -3), array('gender', 'prefix', 'suffix'))) {
825 $row[$field] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $field, $dao->$field);
827 elseif (is_array($value) && $field == 'location') {
828 // fix header for location type case
829 foreach ($value as $ltype => $val) {
830 foreach (array_keys($val) as $fld) {
831 $type = explode('-', $fld);
832 $fldValue = "{$ltype}-" . $type[0];
834 if (CRM_Utils_Array
::value(1, $type)) {
835 $fldValue .= "-" . $type[1];
838 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
842 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'country'));
845 case 'state_province':
846 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'province'));
850 $imFieldvalue = $fldValue . "-provider_id";
851 $row[$fldValue] = CRM_Utils_Array
::value($dao->$imFieldvalue, $imProviders);
855 $row[$fldValue] = $dao->$fldValue;
861 elseif (array_key_exists($field, $contactRelationshipTypes)) {
862 $relDAO = CRM_Utils_Array
::value($dao->contact_id
, $allRelContactArray[$field]);
863 foreach ($value as $relationField => $relationValue) {
864 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
865 $fieldValue = $relDAO->$relationField;
866 if ($relationField == 'phone_type_id') {
867 $fieldValue = $phoneTypes[$relationValue];
869 elseif ($relationField == 'provider_id') {
870 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
874 elseif (is_object($relDAO) && in_array($relationField, array(
875 'email_greeting', 'postal_greeting', 'addressee'))) {
876 //special case for greeting replacement
877 $fldValue = "{$relationField}_display";
878 $fieldValue = $relDAO->$fldValue;
880 elseif ( is_object($relDAO) && $relationField == 'state_province' ) {
881 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
883 elseif ( is_object($relDAO) && $relationField == 'country' ) {
884 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
889 $field = $field . '_';
891 if (is_object($relDAO) && $relationField == 'id') {
892 $row[$field . $relationField] = $relDAO->contact_id
;
894 elseif ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
895 foreach ($relationValue as $ltype => $val) {
896 foreach (array_keys($val) as $fld) {
897 $type = explode('-', $fld);
898 $fldValue = "{$ltype}-" . $type[0];
899 if (CRM_Utils_Array
::value(1, $type)) {
900 $fldValue .= "-" . $type[1];
902 // CRM-3157: localise country, region (both have ‘country’ context)
903 // and state_province (‘province’ context)
905 case (!is_object($relDAO)):
906 $row[$field . '_' . $fldValue] = '';
909 case in_array('country', $type):
910 case in_array('world_region', $type):
911 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
912 array('context' => 'country')
916 case in_array('state_province', $type):
917 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
918 array('context' => 'province')
923 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
929 elseif (isset($fieldValue) && $fieldValue != '') {
930 //check for custom data
931 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
932 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
933 $relationQuery[$field]->_options
937 //normal relationship fields
938 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
939 switch ($relationField) {
942 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
945 case 'state_province':
946 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
950 $row[$field . $relationField] = $fieldValue;
956 // if relation field is empty or null
957 $row[$field . $relationField] = '';
961 elseif (isset($fieldValue) &&
964 //check for custom data
965 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
966 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
968 elseif (array_key_exists($field, $multipleSelectFields)) {
970 $paramsNew = array($field => $fieldValue);
971 if ($field == 'test_tutoring') {
972 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
975 elseif (substr($field, 0, 4) == 'cmr_') {
976 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
979 $name = array($field => array('newName' => $field, 'groupName' => $field));
981 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
982 $row[$field] = $paramsNew[$field];
984 elseif (in_array($field, array(
985 'email_greeting', 'postal_greeting', 'addressee'))) {
986 //special case for greeting replacement
987 $fldValue = "{$field}_display";
988 $row[$field] = $dao->$fldValue;
991 //normal fields with a touch of CRM-3157
995 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
998 case 'state_province':
999 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1003 case 'preferred_communication_method':
1004 case 'preferred_mail_format':
1005 $row[$field] = $i18n->crm_translate($fieldValue);
1009 $row[$field] = $fieldValue;
1014 elseif (substr($field, -8) == 'campaign') {
1015 $campIdFld = "{$field}_id";
1016 $row[$field] = CRM_Utils_Array
::value($dao->$campIdFld, $allCampaigns, '');
1018 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1019 $paymentData = CRM_Utils_Array
::value($dao->$paymentTableId, $paymentDetails);
1020 $payFieldMapper = array(
1021 'componentPaymentField_total_amount' => 'total_amount',
1022 'componentPaymentField_contribution_status' => 'contribution_status',
1023 'componentPaymentField_payment_instrument' => 'pay_instru',
1024 'componentPaymentField_transaction_id' => 'trxn_id',
1025 'componentPaymentField_received_date' => 'receive_date',
1027 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1030 // if field is empty or null
1035 // add payment headers if required
1036 if ($addPaymentHeader && $paymentFields) {
1037 $headerRows = array_merge($headerRows, $paymentHeaders);
1038 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1039 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1044 $exportTempTable = self
::createTempTable($sqlColumns);
1047 //build header only once
1050 // If specific payment fields have been selected for export, payment
1051 // data will already be in $row. Otherwise, add payment related
1052 // information, if appropriate.
1053 if ($addPaymentHeader) {
1054 if (!$selectedPaymentFields) {
1055 if ($paymentFields) {
1056 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1057 if (!is_array($paymentData) ||
empty($paymentData)) {
1058 $paymentData = $nullContributionDetails;
1060 $row = array_merge($row, $paymentData);
1062 elseif (!empty($paymentDetails)) {
1063 $row = array_merge($row, $nullContributionDetails);
1067 //remove organization name for individuals if it is set for current employer
1068 if (CRM_Utils_Array
::value('contact_type', $row) &&
1069 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1071 $row['organization_name'] = '';
1074 // add component info
1075 // write the row to a file
1076 $componentDetails[] = $row;
1078 // output every $tempRowCount rows
1079 if ($count %
$tempRowCount == 0) {
1080 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1081 $componentDetails = array();
1085 $offset +
= $rowCount;
1088 if ($exportTempTable) {
1089 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1091 // do merge same address and merge same household processing
1092 if ($mergeSameAddress) {
1093 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1096 // merge the records if they have corresponding households
1097 if ($mergeSameHousehold) {
1098 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1099 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1102 // fix the headers for rows with relationship type
1103 if (!empty($relName)) {
1104 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1107 // if postalMailing option is checked, exclude contacts who are deceased, have
1108 // "Do not mail" privacy setting, or have no street address
1109 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1110 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1112 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1116 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1118 // now write the CSV file
1119 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1121 // delete the export temp table and component table
1122 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1123 CRM_Core_DAO
::executeQuery($sql);
1125 CRM_Utils_System
::civiExit();
1128 CRM_Core_Error
::fatal(ts('No records to export'));
1133 * name of the export file based on mode
1135 * @param string $output type of output
1136 * @param int $mode export mode
1138 * @return string name of the file
1140 static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1142 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1143 return ts('CiviCRM Contact Search');
1145 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1146 return ts('CiviCRM Contribution Search');
1148 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1149 return ts('CiviCRM Member Search');
1151 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1152 return ts('CiviCRM Participant Search');
1154 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1155 return ts('CiviCRM Pledge Search');
1157 case CRM_Export_Form_Select
::CASE_EXPORT
:
1158 return ts('CiviCRM Case Search');
1160 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1161 return ts('CiviCRM Grant Search');
1163 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1164 return ts('CiviCRM Activity Search');
1169 * Function to handle import error file creation.
1172 static function invoke() {
1173 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1174 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1175 if (empty($parserName) ||
empty($type)) {
1179 // clean and ensure parserName is a valid string
1180 $parserName = CRM_Utils_String
::munge($parserName);
1181 $parserClass = explode('_', $parserName);
1183 // make sure parserClass is in the CRM namespace and
1184 // at least 3 levels deep
1185 if ($parserClass[0] == 'CRM' &&
1186 count($parserClass) >= 3
1188 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php");
1189 // ensure the functions exists
1190 if (method_exists($parserName, 'errorFileName') &&
1191 method_exists($parserName, 'saveFileName')
1193 $errorFileName = $parserName::errorFileName($type);
1194 $saveFileName = $parserName::saveFileName($type);
1195 if (!empty($errorFileName) && !empty($saveFileName)) {
1196 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1197 header('Content-Description: File Transfer');
1198 header('Content-Type: text/csv');
1199 header('Content-Length: ' . filesize($errorFileName));
1200 header('Content-Disposition: attachment; filename=' . $saveFileName);
1202 readfile($errorFileName);
1206 CRM_Utils_System
::civiExit();
1209 static function exportCustom($customSearchClass, $formValues, $order) {
1210 $ext = CRM_Extension_System
::singleton()->getMapper();
1211 if (!$ext->isExtensionClass($customSearchClass)) {
1212 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php');
1215 require_once ($ext->classToPath($customSearchClass));
1217 $search = new $customSearchClass($formValues);
1219 $includeContactIDs = FALSE;
1220 if ($formValues['radio_ts'] == 'ts_sel') {
1221 $includeContactIDs = TRUE;
1224 $sql = $search->all(0, 0, $order, $includeContactIDs);
1226 $columns = $search->columns();
1228 $header = array_keys($columns);
1229 $fields = array_values($columns);
1232 $dao = CRM_Core_DAO
::executeQuery($sql);
1234 if (method_exists($search, 'alterRow')) {
1237 while ($dao->fetch()) {
1240 foreach ($fields as $field) {
1241 $row[$field] = $dao->$field;
1244 $search->alterRow($row);
1249 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1250 CRM_Utils_System
::civiExit();
1253 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1254 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1258 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1259 if ($fieldName == 'id') {
1260 $fieldName = 'civicrm_primary_id';
1263 // early exit for master_id, CRM-12100
1264 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1265 if ($fieldName == 'master_id') {
1266 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1270 // set the sql columns
1271 if (isset($query->_fields
[$field]['type'])) {
1272 switch ($query->_fields
[$field]['type']) {
1273 case CRM_Utils_Type
::T_INT
:
1274 case CRM_Utils_Type
::T_BOOLEAN
:
1275 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1278 case CRM_Utils_Type
::T_STRING
:
1279 if (isset($query->_fields
[$field]['maxlength'])) {
1280 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1283 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1287 case CRM_Utils_Type
::T_TEXT
:
1288 case CRM_Utils_Type
::T_LONGTEXT
:
1289 case CRM_Utils_Type
::T_BLOB
:
1290 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1291 $sqlColumns[$fieldName] = "$fieldName longtext";
1294 case CRM_Utils_Type
::T_FLOAT
:
1295 case CRM_Utils_Type
::T_ENUM
:
1296 case CRM_Utils_Type
::T_DATE
:
1297 case CRM_Utils_Type
::T_TIME
:
1298 case CRM_Utils_Type
::T_TIMESTAMP
:
1299 case CRM_Utils_Type
::T_MONEY
:
1300 case CRM_Utils_Type
::T_EMAIL
:
1301 case CRM_Utils_Type
::T_URL
:
1302 case CRM_Utils_Type
::T_CCNUM
:
1304 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1309 if (substr($fieldName, -3, 3) == '_id') {
1310 // for trxn_id and its variants use a longer buffer
1311 // to accomodate different systems - CRM-13739
1312 static $notRealIDFields = NULL;
1313 if ($notRealIDFields == NULL) {
1314 $notRealIDFields = array( 'trxn_id', 'componentpaymentfield_transaction_id' );
1317 if (in_array($fieldName, $notRealIDFields)) {
1318 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1321 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1325 $changeFields = array(
1331 if (in_array($fieldName, $changeFields)) {
1332 $sqlColumns[$fieldName] = "$fieldName text";
1335 // set the sql columns for custom data
1336 if (isset($query->_fields
[$field]['data_type'])) {
1338 switch ($query->_fields
[$field]['data_type']) {
1340 case 'StateProvince':
1343 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1347 $sqlColumns[$fieldName] = "$fieldName text";
1351 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1356 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1363 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1364 if (empty($details)) {
1373 $id = CRM_Core_DAO
::singleValueQuery($sql);
1378 $sqlClause = array();
1380 foreach ($details as $dontCare => $row) {
1382 $valueString = array($id);
1383 foreach ($row as $dontCare => $value) {
1384 if (empty($value)) {
1385 $valueString[] = "''";
1388 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1391 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1394 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1396 $sqlValueString = implode(",\n", $sqlClause);
1399 INSERT INTO $tableName $sqlColumnString
1400 VALUES $sqlValueString
1403 CRM_Core_DAO
::executeQuery($sql);
1406 static function createTempTable(&$sqlColumns) {
1407 //creating a temporary table for the search result that need be exported
1408 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1410 // also create the sql table
1411 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1412 CRM_Core_DAO
::executeQuery($sql);
1415 CREATE TABLE {$exportTempTable} (
1416 id int unsigned NOT NULL AUTO_INCREMENT,
1418 $sql .= implode(",\n", array_values($sqlColumns));
1423 // add indexes for street_address and household_name if present
1424 $addIndices = array(
1427 'civicrm_primary_id',
1430 foreach ($addIndices as $index) {
1431 if (isset($sqlColumns[$index])) {
1433 INDEX index_{$index}( $index )
1439 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1442 CRM_Core_DAO
::executeQuery($sql);
1443 return $exportTempTable;
1446 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1447 // check if any records are present based on if they have used shared address feature,
1448 // and not based on if city / state .. matches.
1450 SELECT r1.id as copy_id,
1451 r1.civicrm_primary_id as copy_contact_id,
1452 r1.addressee as copy_addressee,
1453 r1.addressee_id as copy_addressee_id,
1454 r1.postal_greeting as copy_postal_greeting,
1455 r1.postal_greeting_id as copy_postal_greeting_id,
1457 r2.civicrm_primary_id as master_contact_id,
1458 r2.postal_greeting as master_postal_greeting,
1459 r2.postal_greeting_id as master_postal_greeting_id,
1460 r2.addressee as master_addressee,
1461 r2.addressee_id as master_addressee_id
1463 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1464 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1466 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1468 // find all the records that have the same street address BUT not in a household
1469 // require match on city and state as well
1471 SELECT r1.id as master_id,
1472 r1.civicrm_primary_id as master_contact_id,
1473 r1.postal_greeting as master_postal_greeting,
1474 r1.postal_greeting_id as master_postal_greeting_id,
1475 r1.addressee as master_addressee,
1476 r1.addressee_id as master_addressee_id,
1478 r2.civicrm_primary_id as copy_contact_id,
1479 r2.postal_greeting as copy_postal_greeting,
1480 r2.postal_greeting_id as copy_postal_greeting_id,
1481 r2.addressee as copy_addressee,
1482 r2.addressee_id as copy_addressee_id
1484 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1485 r1.city = r2.city AND
1486 r1.state_province_id = r2.state_province_id )
1487 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1488 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1489 AND ( r1.street_address != '' )
1493 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1495 // unset ids from $merge already present in $linkedMerge
1496 foreach ($linkedMerge as $masterID => $values) {
1497 $keys = array($masterID);
1498 $keys = array_merge($keys, array_keys($values['copy']));
1499 foreach ($merge as $mid => $vals) {
1500 if (in_array($mid, $keys)) {
1501 unset($merge[$mid]);
1504 foreach ($values['copy'] as $copyId) {
1505 if (in_array($copyId, $keys)) {
1506 unset($merge[$mid]['copy'][$copyId]);
1512 $merge = $merge +
$linkedMerge;
1514 foreach ($merge as $masterID => $values) {
1517 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1520 $params = array(1 => array($values['addressee'], 'String'),
1521 2 => array($values['postalGreeting'], 'String'),
1522 3 => array($values['emailGreeting'], 'String'),
1523 4 => array($masterID, 'Integer'),
1525 CRM_Core_DAO
::executeQuery($sql, $params);
1527 // delete all copies
1528 $deleteIDs = array_keys($values['copy']);
1529 $deleteIDString = implode(',', $deleteIDs);
1531 DELETE FROM $tableName
1532 WHERE id IN ( $deleteIDString )
1534 CRM_Core_DAO
::executeQuery($sql);
1537 // unset temporary columns that were added for postal mailing format
1538 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1539 $unsetKeys = array_keys($sqlColumns);
1540 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1541 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1542 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1548 static function _replaceMergeTokens($contactId, $exportParams) {
1549 $greetings = array();
1552 $greetingFields = array(
1556 foreach ($greetingFields as $greeting) {
1557 if (CRM_Utils_Array
::value($greeting, $exportParams)) {
1558 $greetingLabel = $exportParams[$greeting];
1559 if (empty($contact)) {
1564 $contact = civicrm_api('contact', 'get', $values);
1566 if (CRM_Utils_Array
::value('is_error', $contact)) {
1569 $contact = $contact['values'][$contact['id']];
1572 $tokens = array('contact' => $greetingLabel);
1573 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1580 * The function unsets static part of the string, if token is the dynamic part.
1581 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1582 * i.e 'Hello Alan' => converted to => 'Alan'
1585 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1586 $addressMergeGreetings, $greetingType = 'postal_greeting'
1588 if (CRM_Utils_Array
::value($greetingType, $addressMergeGreetings)) {
1589 $greetingLabel = $addressMergeGreetings[$greetingType];
1591 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1593 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1594 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1595 foreach ($stringsToBeReplaced as $key => $string) {
1596 // to keep one space
1597 $stringsToBeReplaced[$key] = ltrim($string);
1599 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1601 return $parsedString;
1604 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1605 static $contactGreetingTokens = array();
1607 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1608 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1610 $merge = $parents = array();
1611 $dao = CRM_Core_DAO
::executeQuery($sql);
1613 while ($dao->fetch()) {
1614 $masterID = $dao->master_id
;
1615 $copyID = $dao->copy_id
;
1616 $masterPostalGreeting = $dao->master_postal_greeting
;
1617 $masterAddressee = $dao->master_addressee
;
1618 $copyAddressee = $dao->copy_addressee
;
1620 if (!$sharedAddress) {
1621 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1622 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1624 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1625 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1627 $masterAddressee = CRM_Utils_Array
::value('addressee',
1628 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1631 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1632 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1634 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1635 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1637 $copyAddressee = CRM_Utils_Array
::value('addressee',
1638 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1642 if (!isset($merge[$masterID])) {
1643 // check if this is an intermediate child
1644 // this happens if there are 3 or more matches a,b, c
1645 // the above query will return a, b / a, c / b, c
1646 // we might be doing a bit more work, but for now its ok, unless someone
1647 // knows how to fix the query above
1648 if (isset($parents[$masterID])) {
1649 $masterID = $parents[$masterID];
1652 $merge[$masterID] = array(
1653 'addressee' => $masterAddressee,
1655 'postalGreeting' => $masterPostalGreeting,
1657 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1660 $parents[$copyID] = $masterID;
1662 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1664 if (CRM_Utils_Array
::value('postal_greeting_other', $exportParams) &&
1665 count($merge[$masterID]['copy']) >= 1
1667 // use static greetings specified if no of contacts > 2
1668 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1670 elseif ($copyPostalGreeting) {
1671 self
::_trimNonTokens($copyPostalGreeting,
1672 $postalOptions[$dao->copy_postal_greeting_id
],
1675 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1676 // if there happens to be a duplicate, remove it
1677 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1680 if (CRM_Utils_Array
::value('addressee_other', $exportParams) &&
1681 count($merge[$masterID]['copy']) >= 1
1683 // use static greetings specified if no of contacts > 2
1684 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1686 elseif ($copyAddressee) {
1687 self
::_trimNonTokens($copyAddressee,
1688 $addresseeOptions[$dao->copy_addressee_id
],
1689 $exportParams, 'addressee'
1691 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1694 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1701 * Function to merge household record into the individual record
1704 * @param string $exportTempTable temporary temp table that stores the records
1705 * @param array $headerRows array of headers for the export file
1706 * @param array $sqlColumns array of names of the table columns of the temp table
1707 * @param string $prefix name of the relationship type that is prefixed to the table columns
1709 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1710 $prefixColumn = $prefix . '_';
1711 $allKeys = array_keys($sqlColumns);
1712 $replaced = array();
1713 $headerRows = array_values($headerRows);
1715 // name map of the non standard fields in header rows & sql columns
1716 $mappingFields = array(
1717 'civicrm_primary_id' => 'id',
1718 'contact_source' => 'source',
1719 'current_employer_id' => 'employer_id',
1720 'contact_is_deleted' => 'is_deleted',
1721 'name' => 'address_name',
1722 'provider_id' => 'im_service_provider',
1723 'phone_type_id' => 'phone_type'
1726 //figure out which columns are to be replaced by which ones
1727 foreach ($sqlColumns as $columnNames => $dontCare) {
1728 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1729 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1732 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1734 if (CRM_Utils_Array
::value($householdColName, $sqlColumns)) {
1735 $replaced[$columnNames] = $householdColName;
1739 $query = "UPDATE $exportTempTable SET ";
1742 foreach ($replaced as $from => $to) {
1743 $clause[] = "$from = $to ";
1744 unset($sqlColumns[$to]);
1745 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1746 unset($headerRows[$key]);
1749 $query .= implode(",\n", $clause);
1750 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1752 CRM_Core_DAO
::executeQuery($query);
1754 //drop the table columns that store redundant household info
1755 $dropQuery = "ALTER TABLE $exportTempTable ";
1756 foreach ($replaced as $householdColumns) {
1757 $dropClause[] = " DROP $householdColumns ";
1759 $dropQuery .= implode(",\n", $dropClause);
1761 CRM_Core_DAO
::executeQuery($dropQuery);
1763 // also drop the temp table if exists
1764 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1765 CRM_Core_DAO
::executeQuery($sql);
1767 // clean up duplicate records
1769 CREATE TABLE {$exportTempTable}_temp SELECT *
1770 FROM {$exportTempTable}
1771 GROUP BY civicrm_primary_id ";
1773 CRM_Core_DAO
::executeQuery($query);
1775 $query = "DROP TABLE $exportTempTable";
1776 CRM_Core_DAO
::executeQuery($query);
1778 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1779 CRM_Core_DAO
::executeQuery($query);
1782 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1783 $writeHeader = TRUE;
1785 $limit = self
::EXPORT_ROW_COUNT
;
1787 $query = "SELECT * FROM $exportTempTable";
1790 $limitQuery = $query . "
1791 LIMIT $offset, $limit
1793 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1799 $componentDetails = array();
1800 while ($dao->fetch()) {
1803 foreach ($sqlColumns as $column => $dontCare) {
1804 $row[$column] = $dao->$column;
1806 $componentDetails[] = $row;
1808 if ( $exportMode == 'financial' ) {
1809 $getExportFileName = 'CiviCRM Contribution Search';
1812 $getExportFileName =self
::getExportFileName( 'csv', $exportMode );
1814 $csvRows = CRM_Core_Report_Excel
::writeCSVFile( $getExportFileName,
1821 if ($saveFile && !empty($csvRows)) {
1822 $batchItems .= $csvRows;
1825 $writeHeader = false;
1831 * Function to manipulate header rows for relationship fields
1834 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1835 foreach ($headerRows as & $header) {
1836 $split = explode('-', $header);
1837 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1838 $split[0] = $relationTypeName;
1839 $header = implode('-', $split);
1845 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1846 * or have no street address
1849 static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1850 $whereClause = array();
1852 if (array_key_exists('is_deceased', $sqlColumns)) {
1853 $whereClause[] = 'is_deceased = 1';
1856 if (array_key_exists('do_not_mail', $sqlColumns)) {
1857 $whereClause[] = 'do_not_mail = 1';
1860 if (array_key_exists('street_address', $sqlColumns)) {
1861 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1863 // check for supplemental_address_1
1864 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1865 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1866 'address_options', TRUE, NULL, TRUE
1868 if (CRM_Utils_Array
::value('supplemental_address_1', $addressOptions)) {
1869 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1870 // enclose it again, since we are doing an AND in between a set of ORs
1871 $addressWhereClause = "( $addressWhereClause )";
1875 $whereClause[] = $addressWhereClause;
1878 if (!empty($whereClause)) {
1879 $whereClause = implode(' OR ', $whereClause);
1882 FROM $exportTempTable
1883 WHERE {$whereClause}";
1884 CRM_Core_DAO
::singleValueQuery($query);
1887 // unset temporary columns that were added for postal mailing format
1888 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1889 $unsetKeys = array_keys($sqlColumns);
1890 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1891 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1892 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1899 * Build componentPayment fields.
1901 static function componentPaymentFields() {
1902 static $componentPaymentFields;
1903 if (!isset( $componentPaymentFields)) {
1904 $componentPaymentFields = array(
1905 'componentPaymentField_total_amount' => ts('Total Amount'),
1906 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1907 'componentPaymentField_received_date' => ts('Received Date'),
1908 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1909 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1912 return $componentPaymentFields;