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();
84 $exportCampaign = FALSE;
86 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
87 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
88 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
97 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
99 switch ($exportMode) {
100 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
101 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
104 case CRM_Export_Form_Select
::EVENT_EXPORT
:
105 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
108 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
109 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
112 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
113 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
116 case CRM_Export_Form_Select
::CASE_EXPORT
:
117 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
120 case CRM_Export_Form_Select
::GRANT_EXPORT
:
121 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
124 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
125 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
129 //construct return properties
130 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
131 $locationTypeFields = array(
133 'supplemental_address_1',
134 'supplemental_address_2',
137 'postal_code_suffix',
147 foreach ($fields as $key => $value) {
148 $phoneTypeId = $imProviderId = NULL;
149 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
153 // get phoneType id and IM service provider id seperately
154 if ($fieldName == 'phone') {
155 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
157 elseif ($fieldName == 'im') {
158 $imProviderId = CRM_Utils_Array
::value(3, $value);
160 elseif (substr($fieldName, -8) == 'campaign') {
161 $exportCampaign = TRUE;
164 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
165 if (CRM_Utils_Array
::value(2, $value)) {
166 $relationField = CRM_Utils_Array
::value(2, $value);
167 if (trim(CRM_Utils_Array
::value(3, $value))) {
168 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
171 $relLocTypeId = 'Primary';
174 if ($relationField == 'phone') {
175 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
177 elseif ($relationField == 'im') {
178 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
181 elseif (CRM_Utils_Array
::value(4, $value)) {
182 $relationField = CRM_Utils_Array
::value(4, $value);
183 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
184 if ($relationField == 'phone') {
185 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
187 elseif ($relationField == 'im') {
188 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
193 $contactType = CRM_Utils_Array
::value(0, $value);
194 $locTypeId = CRM_Utils_Array
::value(2, $value);
196 if ($relationField) {
197 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
198 if ($relPhoneTypeId) {
199 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
201 elseif ($relIMProviderId) {
202 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
205 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
207 $relPhoneTypeId = $relIMProviderId = NULL;
210 $returnProperties[$relationshipTypes][$relationField] = 1;
213 elseif (is_numeric($locTypeId)) {
215 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
217 elseif ($imProviderId) {
218 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
221 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
225 //hack to fix component fields
226 if ($fieldName == 'event_id') {
227 $returnProperties['event_title'] = 1;
230 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
231 array_key_exists( $fieldName, self
::componentPaymentFields())
233 $selectedPaymentFields = true;
234 $paymentTableId = 'participant_id';
235 $returnProperties[$fieldName] = 1;
238 $returnProperties[$fieldName] = 1;
240 //campaign field export.
241 if (substr($fieldName, -8) == 'campaign') {
242 $fldNames = explode('_', $fieldName);
243 $returnProperties["{$fldNames[0]}_campaign_id"] = 1;
249 // hack to add default returnproperty based on export mode
250 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
251 $returnProperties['contribution_id'] = 1;
253 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
254 $returnProperties['participant_id'] = 1;
255 if (CRM_Utils_Array
::value('participant_role', $returnProperties)) {
256 unset($returnProperties['participant_role']);
257 $returnProperties['participant_role_id'] = 1;
260 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
261 $returnProperties['membership_id'] = 1;
263 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
264 $returnProperties['pledge_id'] = 1;
266 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
267 $returnProperties['case_id'] = 1;
269 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
270 $returnProperties['grant_id'] = 1;
272 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
273 $returnProperties['activity_id'] = 1;
278 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
279 foreach ($fields as $key => $var) {
280 if ($key && (substr($key, 0, 6) != 'custom')) {
282 $returnProperties[$key] = 1;
287 $returnProperties['location_type'] = 1;
288 $returnProperties['im_provider'] = 1;
289 $returnProperties['phone_type_id'] = 1;
290 $returnProperties['provider_id'] = 1;
291 $returnProperties['current_employer'] = 1;
294 $extraReturnProperties = array();
295 $paymentFields = FALSE;
297 switch ($queryMode) {
298 case CRM_Contact_BAO_Query
::MODE_EVENT
:
299 $paymentFields = TRUE;
300 $paymentTableId = 'participant_id';
303 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
304 $paymentFields = TRUE;
305 $paymentTableId = 'membership_id';
308 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
309 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
310 $paymentFields = TRUE;
311 $paymentTableId = 'pledge_payment_id';
314 case CRM_Contact_BAO_Query
::MODE_CASE
:
315 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
319 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
320 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
322 $campaignReturnProperties = array();;
323 foreach ($componentReturnProperties as $fld => $true) {
324 $campaignReturnProperties[$fld] = $true;
325 if (substr($fld, -11) == 'campaign_id') {
326 $exportCampaign = TRUE;
327 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
330 $componentReturnProperties = $campaignReturnProperties;
332 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
334 if (!empty($extraReturnProperties)) {
335 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
338 // unset non exportable fields for components
339 $nonExpoFields = array(
340 'groups', 'tags', 'notes', 'contribution_status_id',
341 'pledge_status_id', 'pledge_payment_status_id',
343 foreach ($nonExpoFields as $value) {
344 unset($returnProperties[$value]);
349 if ($mergeSameAddress) {
350 //make sure the addressee fields are selected
351 //while using merge same address feature
352 $returnProperties['addressee'] = 1;
353 $returnProperties['postal_greeting'] = 1;
354 $returnProperties['email_greeting'] = 1;
355 $returnProperties['street_name'] = 1;
356 $returnProperties['household_name'] = 1;
357 $returnProperties['street_address'] = 1;
358 $returnProperties['city'] = 1;
359 $returnProperties['state_province'] = 1;
361 // some columns are required for assistance incase they are not already present
362 $exportParams['merge_same_address']['temp_columns'] = array();
363 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
364 foreach ($tempColumns as $column) {
365 if (!array_key_exists($column, $returnProperties)) {
366 $returnProperties[$column] = 1;
367 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
368 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
373 if (!$selectAll && $componentTable && CRM_Utils_Array
::value('additional_group', $exportParams)) {
374 // If an Additional Group is selected, then all contacts in that group are
375 // added to the export set (filtering out duplicates).
377 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";
378 CRM_Core_DAO
::executeQuery($query);
381 if ($moreReturnProperties) {
383 if (CRM_Utils_Array
::value('group', $moreReturnProperties)) {
384 unset($moreReturnProperties['group']);
385 $moreReturnProperties['groups'] = 1;
387 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
390 $exportParams['postal_mailing_export']['temp_columns'] = array();
391 if ($exportParams['exportOption'] == 2 &&
392 isset($exportParams['postal_mailing_export']) &&
393 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
395 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
396 foreach ($postalColumns as $column) {
397 if (!array_key_exists($column, $returnProperties)) {
398 $returnProperties[$column] = 1;
399 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
404 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
405 FALSE, FALSE, $queryMode,
406 FALSE, TRUE, TRUE, NULL, $queryOperator
409 list($select, $from, $where, $having) = $query->query();
411 if ($mergeSameHousehold == 1) {
412 if (!$returnProperties['id']) {
413 $returnProperties['id'] = 1;
416 //also merge Head of Household
417 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
418 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
420 foreach ($returnProperties as $key => $value) {
421 if (!array_key_exists($key, $contactRelationshipTypes)) {
422 $returnProperties[$relationKeyMOH][$key] = $value;
423 $returnProperties[$relationKeyHOH][$key] = $value;
427 unset($returnProperties[$relationKeyMOH]['location_type']);
428 unset($returnProperties[$relationKeyMOH]['im_provider']);
429 unset($returnProperties[$relationKeyHOH]['location_type']);
430 unset($returnProperties[$relationKeyHOH]['im_provider']);
433 $allRelContactArray = $relationQuery = array();
435 foreach ($contactRelationshipTypes as $rel => $dnt) {
436 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
437 $allRelContactArray[$rel] = array();
438 // build Query for each relationship
439 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
440 NULL, FALSE, FALSE, $queryMode
442 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
444 list($id, $direction) = explode('_', $rel, 2);
445 // identify the relationship direction
446 $contactA = 'contact_id_a';
447 $contactB = 'contact_id_b';
448 if ($direction == 'b_a') {
449 $contactA = 'contact_id_b';
450 $contactB = 'contact_id_a';
452 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
455 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
456 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
457 $query = "SELECT contact_id FROM civicrm_activity_contact
458 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
459 record_type_id = {$sourceID}";
460 $dao = CRM_Core_DAO
::executeQuery($query);
461 while ($dao->fetch()) {
462 $relIDs[] = $dao->contact_id
;
466 switch ($exportMode) {
467 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
468 $component = 'civicrm_contribution';
471 case CRM_Export_Form_Select
::EVENT_EXPORT
:
472 $component = 'civicrm_participant';
475 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
476 $component = 'civicrm_membership';
479 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
480 $component = 'civicrm_pledge';
483 case CRM_Export_Form_Select
::GRANT_EXPORT
:
484 $component = 'civicrm_grant';
488 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
489 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
492 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
496 $relationshipJoin = $relationshipClause = '';
497 if (!$selectAll && $componentTable) {
498 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
500 elseif (!empty($relIDs)) {
501 $relID = implode(',', $relIDs);
502 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
505 $relationFrom = " {$relationFrom}
506 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
507 {$relationshipJoin} ";
509 //check for active relationship status only
510 $today = date('Ymd');
511 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
512 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
513 $relationGroupBy = " GROUP BY crel.{$contactA}";
514 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
515 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
517 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
518 while ($allRelContactDAO->fetch()) {
519 //FIX Me: Migrate this to table rather than array
520 // build the array of all related contacts
521 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
523 $allRelContactDAO->free();
527 // make sure the groups stuff is included only if specifically specified
528 // by the fields param (CRM-1969), else we limit the contacts outputted to only
529 // ones that are part of a group
530 if (CRM_Utils_Array
::value('groups', $returnProperties)) {
531 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
532 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
533 // total hack for export, CRM-3618
534 $from = str_replace($oldClause,
540 if (!$selectAll && $componentTable) {
541 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
543 elseif ($componentClause) {
545 $where = "WHERE $componentClause";
548 $where .= " AND $componentClause";
552 $queryString = "$select $from $where $having";
555 if (CRM_Utils_Array
::value('tags', $returnProperties) ||
556 CRM_Utils_Array
::value('groups', $returnProperties) ||
557 CRM_Utils_Array
::value('notes', $returnProperties) ||
559 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
561 $groupBy = " GROUP BY contact_a.id";
564 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
565 $groupBy = " GROUP BY civicrm_activity.id ";
567 $queryString .= $groupBy;
569 list($field, $dir) = explode(' ', $order, 2);
570 $field = trim($field);
571 if (CRM_Utils_Array
::value($field, $returnProperties)) {
572 // $queryString .= " ORDER BY $order";
576 $multipleSelectFields = array('preferred_communication_method' => 1);
578 $addPaymentHeader = FALSE;
580 $paymentDetails = array();
581 if ($paymentFields ||
$selectedPaymentFields) {
583 // get payment related in for event and members
584 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
585 //get all payment headers.
586 // If we haven't selected specific payment fields, load in all the
588 if (!$selectedPaymentFields) {
589 $paymentHeaders = self
::componentPaymentFields();
590 if (!empty($paymentDetails)) {
591 $addPaymentHeader = TRUE;
594 // If we have seleted specific payment fields, leave the payment headers
595 // as an empty array; the headers for each selected field will be added
598 $paymentHeaders = array();
600 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
604 if ($exportCampaign) {
605 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
608 $componentDetails = $headerRows = $sqlColumns = array();
611 $rowCount = self
::EXPORT_ROW_COUNT
;
613 // we write to temp table often to avoid using too much memory
618 // for CRM-3157 purposes
619 $i18n = CRM_Core_I18n
::singleton();
622 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
623 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
628 while ($dao->fetch()) {
632 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
633 //convert the pseudo constants
634 $query->convertToPseudoNames($dao);
637 //first loop through returnproperties so that we return what is required, and in same order.
638 $relationshipField = 0;
639 foreach ($returnProperties as $field => $value) {
640 //we should set header only once
643 if (isset($query->_fields
[$field]['title'])) {
644 $headerRows[] = $query->_fields
[$field]['title'];
646 elseif ($field == 'phone_type_id') {
647 $headerRows[] = ts('Phone Type');
649 elseif ($field == 'provider_id') {
650 $headerRows[] = ts('IM Service Provider');
652 elseif (is_array($value) && $field == 'location') {
653 // fix header for location type case
654 foreach ($value as $ltype => $val) {
655 foreach (array_keys($val) as $fld) {
656 $type = explode('-', $fld);
657 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
659 if (CRM_Utils_Array
::value(1, $type)) {
660 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
661 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
663 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
664 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
667 $headerRows[] = $hdr;
668 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
673 elseif (substr($field, 0, 5) == 'case_') {
674 if ($query->_fields
['case'][$field]['title']) {
675 $headerRows[] = $query->_fields
['case'][$field]['title'];
677 elseif ($query->_fields
['activity'][$field]['title']) {
678 $headerRows[] = $query->_fields
['activity'][$field]['title'];
681 elseif (array_key_exists($field, $contactRelationshipTypes)) {
683 foreach ($value as $relationField => $relationValue) {
684 // below block is same as primary block (duplicate)
685 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
686 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
687 $headerName = $field . '-' . $relationField;
690 if ($relationField == 'current_employer') {
691 $headerName = $field . '-' . 'current_employer';
694 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
698 $headerRows[] = $headerName;
700 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
702 elseif ($relationField == 'phone_type_id') {
703 $headerName = $field . '-' . 'Phone Type';
704 $headerRows[] = $headerName;
705 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
707 elseif ($relationField == 'provider_id') {
708 $headerName = $field . '-' . 'Im Service Provider';
709 $headerRows[] = $headerName;
710 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
712 elseif ($relationField == 'state_province_id') {
713 $headerName = $field . '-' . 'state_province_id';
714 $headerRows[] = $headerName;
715 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
717 elseif (is_array($relationValue) && $relationField == 'location') {
718 // fix header for location type case
719 foreach ($relationValue as $ltype => $val) {
720 foreach (array_keys($val) as $fld) {
721 $type = explode('-', $fld);
723 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
725 if (CRM_Utils_Array
::value(1, $type)) {
726 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
727 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
729 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
730 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
733 $headerName = $field . '-' . $hdr;
734 $headerRows[] = $headerName;
735 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
741 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
742 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
745 $headerRows[] = $field;
749 self
::sqlColumnDefn($query, $sqlColumns, $field);
753 // add im_provider to $dao object
754 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
755 $dao->im_provider
= $dao->provider_id
;
758 //build row values (data)
760 if (property_exists($dao, $field)) {
761 $fieldValue = $dao->$field;
762 // to get phone type from phone type id
763 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
764 $fieldValue = $phoneTypes[$fieldValue];
766 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
767 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
769 elseif ($field == 'participant_role_id') {
770 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
771 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
772 $viewRoles = array();
773 foreach (explode($sep, $dao->$field) as $k => $v) {
774 $viewRoles[] = $participantRoles[$v];
776 $fieldValue = implode(',', $viewRoles);
778 elseif ($field == 'master_id') {
779 $masterAddressId = NULL;
780 if (isset($dao->master_id
)) {
781 $masterAddressId = $dao->master_id
;
783 // get display name of contact that address is shared.
784 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $dao->contact_id
);
788 if ($field == 'id') {
789 $row[$field] = $dao->contact_id
;
790 // special case for calculated field
792 elseif ($field == 'source_contact_id') {
793 $row[$field] = $dao->contact_id
;
795 elseif ($field == 'pledge_balance_amount') {
796 $row[$field] = $dao->pledge_amount
- $dao->pledge_total_paid
;
797 // special case for calculated field
799 elseif ($field == 'pledge_next_pay_amount') {
800 $row[$field] = $dao->pledge_next_pay_amount +
$dao->pledge_outstanding_amount
;
802 elseif (in_array(substr($field, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
803 $row[$field] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $field, $dao->$field);
805 elseif (is_array($value) && $field == 'location') {
806 // fix header for location type case
807 foreach ($value as $ltype => $val) {
808 foreach (array_keys($val) as $fld) {
809 $type = explode('-', $fld);
810 $fldValue = "{$ltype}-" . $type[0];
812 if (CRM_Utils_Array
::value(1, $type)) {
813 $fldValue .= "-" . $type[1];
816 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
820 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'country'));
823 case 'state_province':
824 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'province'));
828 $imFieldvalue = $fldValue . "-provider_id";
829 $row[$fldValue] = CRM_Utils_Array
::value($dao->$imFieldvalue, $imProviders);
833 $row[$fldValue] = $dao->$fldValue;
839 elseif (array_key_exists($field, $contactRelationshipTypes)) {
840 $relDAO = CRM_Utils_Array
::value($dao->contact_id
, $allRelContactArray[$field]);
841 foreach ($value as $relationField => $relationValue) {
842 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
843 $fieldValue = $relDAO->$relationField;
844 if ($relationField == 'phone_type_id') {
845 $fieldValue = $phoneTypes[$relationValue];
847 elseif ($relationField == 'provider_id') {
848 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
854 $field = $field . '_';
855 if (is_object($relDAO) && $relationField == 'id') {
856 $row[$field . $relationField] = $relDAO->contact_id
;
857 } else if ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
858 foreach ($relationValue as $ltype => $val) {
859 foreach (array_keys($val) as $fld) {
860 $type = explode('-', $fld);
861 $fldValue = "{$ltype}-" . $type[0];
862 if (CRM_Utils_Array
::value(1, $type)) {
863 $fldValue .= "-" . $type[1];
865 // CRM-3157: localise country, region (both have ‘country’ context)
866 // and state_province (‘province’ context)
868 case (!is_object($relDAO)):
869 $row[$field . '_' . $fldValue] = '';
872 case in_array('country', $type):
873 case in_array('world_region', $type):
874 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
875 array('context' => 'country')
879 case in_array('state_province', $type):
880 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
881 array('context' => 'province')
886 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
892 elseif (isset($fieldValue) && $fieldValue != '') {
893 //check for custom data
894 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
895 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
896 $relationQuery[$field]->_options
899 elseif (in_array($relationField, array(
900 'email_greeting', 'postal_greeting', 'addressee'))) {
901 //special case for greeting replacement
902 $fldValue = "{$relationField}_display";
903 $row[$field . $relationField] = $relDAO->$fldValue;
906 //normal relationship fields
907 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
908 switch ($relationField) {
911 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
914 case 'state_province':
915 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
919 $row[$field . $relationField] = $fieldValue;
925 // if relation field is empty or null
926 $row[$field . $relationField] = '';
930 elseif (isset($fieldValue) &&
933 //check for custom data
934 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
935 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
937 elseif (array_key_exists($field, $multipleSelectFields)) {
939 $paramsNew = array($field => $fieldValue);
940 if ($field == 'test_tutoring') {
941 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
944 elseif (substr($field, 0, 4) == 'cmr_') {
945 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
948 $name = array($field => array('newName' => $field, 'groupName' => $field));
950 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
951 $row[$field] = $paramsNew[$field];
953 elseif (in_array($field, array(
954 'email_greeting', 'postal_greeting', 'addressee'))) {
955 //special case for greeting replacement
956 $fldValue = "{$field}_display";
957 $row[$field] = $dao->$fldValue;
960 //normal fields with a touch of CRM-3157
964 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
967 case 'state_province':
968 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
972 case 'preferred_communication_method':
973 case 'preferred_mail_format':
974 case 'communication_style':
975 $row[$field] = $i18n->crm_translate($fieldValue);
979 $row[$field] = $fieldValue;
984 elseif (substr($field, -8) == 'campaign') {
985 $campIdFld = "{$field}_id";
986 $row[$field] = CRM_Utils_Array
::value($dao->$campIdFld, $allCampaigns, '');
988 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
989 $paymentData = CRM_Utils_Array
::value($dao->$paymentTableId, $paymentDetails);
990 $payFieldMapper = array(
991 'componentPaymentField_total_amount' => 'total_amount',
992 'componentPaymentField_contribution_status' => 'contribution_status',
993 'componentPaymentField_payment_instrument' => 'pay_instru',
994 'componentPaymentField_transaction_id' => 'trxn_id',
995 'componentPaymentField_received_date' => 'receive_date',
997 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1000 // if field is empty or null
1005 // add payment headers if required
1006 if ($addPaymentHeader && $paymentFields) {
1007 $headerRows = array_merge($headerRows, $paymentHeaders);
1008 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1009 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1014 $exportTempTable = self
::createTempTable($sqlColumns);
1017 //build header only once
1020 // If specific payment fields have been selected for export, payment
1021 // data will already be in $row. Otherwise, add payment related
1022 // information, if appropriate.
1023 if ($addPaymentHeader) {
1024 if (!$selectedPaymentFields) {
1025 if ($paymentFields) {
1026 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1027 if (!is_array($paymentData) ||
empty($paymentData)) {
1028 $paymentData = $nullContributionDetails;
1030 $row = array_merge($row, $paymentData);
1032 elseif (!empty($paymentDetails)) {
1033 $row = array_merge($row, $nullContributionDetails);
1037 //remove organization name for individuals if it is set for current employer
1038 if (CRM_Utils_Array
::value('contact_type', $row) &&
1039 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1041 $row['organization_name'] = '';
1044 // add component info
1045 // write the row to a file
1046 $componentDetails[] = $row;
1048 // output every $tempRowCount rows
1049 if ($count %
$tempRowCount == 0) {
1050 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1051 $componentDetails = array();
1055 $offset +
= $rowCount;
1058 if ($exportTempTable) {
1059 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1061 // do merge same address and merge same household processing
1062 if ($mergeSameAddress) {
1063 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1066 // merge the records if they have corresponding households
1067 if ($mergeSameHousehold) {
1068 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1069 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1072 // fix the headers for rows with relationship type
1073 if (!empty($relName)) {
1074 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1077 // if postalMailing option is checked, exclude contacts who are deceased, have
1078 // "Do not mail" privacy setting, or have no street address
1079 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1080 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1082 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1086 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1088 // now write the CSV file
1089 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1091 // delete the export temp table and component table
1092 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1093 CRM_Core_DAO
::executeQuery($sql);
1095 CRM_Utils_System
::civiExit();
1098 CRM_Core_Error
::fatal(ts('No records to export'));
1103 * name of the export file based on mode
1105 * @param string $output type of output
1106 * @param int $mode export mode
1108 * @return string name of the file
1110 static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1112 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1113 return ts('CiviCRM Contact Search');
1115 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1116 return ts('CiviCRM Contribution Search');
1118 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1119 return ts('CiviCRM Member Search');
1121 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1122 return ts('CiviCRM Participant Search');
1124 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1125 return ts('CiviCRM Pledge Search');
1127 case CRM_Export_Form_Select
::CASE_EXPORT
:
1128 return ts('CiviCRM Case Search');
1130 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1131 return ts('CiviCRM Grant Search');
1133 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1134 return ts('CiviCRM Activity Search');
1139 * Function to handle import error file creation.
1143 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1144 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1145 if (empty($parserName) ||
empty($type)) {
1149 // clean and ensure parserName is a valid string
1150 $parserName = CRM_Utils_String
::munge($parserName);
1151 $parserClass = explode('_', $parserName);
1153 // make sure parserClass is in the CRM namespace and
1154 // at least 3 levels deep
1155 if ($parserClass[0] == 'CRM' &&
1156 count($parserClass) >= 3
1158 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php");
1159 // ensure the functions exists
1160 if (method_exists($parserName, 'errorFileName') &&
1161 method_exists($parserName, 'saveFileName')
1163 $errorFileName = $parserName::errorFileName($type);
1164 $saveFileName = $parserName::saveFileName($type);
1165 if (!empty($errorFileName) && !empty($saveFileName)) {
1166 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1167 header('Content-Description: File Transfer');
1168 header('Content-Type: text/csv');
1169 header('Content-Length: ' . filesize($errorFileName));
1170 header('Content-Disposition: attachment; filename=' . $saveFileName);
1172 readfile($errorFileName);
1176 CRM_Utils_System
::civiExit();
1179 function exportCustom($customSearchClass, $formValues, $order) {
1180 $ext = CRM_Extension_System
::singleton()->getMapper();
1181 if (!$ext->isExtensionClass($customSearchClass)) {
1182 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php');
1185 require_once ($ext->classToPath($customSearchClass));
1187 $search = new $customSearchClass($formValues);
1189 $includeContactIDs = FALSE;
1190 if ($formValues['radio_ts'] == 'ts_sel') {
1191 $includeContactIDs = TRUE;
1194 $sql = $search->all(0, 0, $order, $includeContactIDs);
1196 $columns = $search->columns();
1198 $header = array_keys($columns);
1199 $fields = array_values($columns);
1202 $dao = CRM_Core_DAO
::executeQuery($sql);
1204 if (method_exists($search, 'alterRow')) {
1207 while ($dao->fetch()) {
1210 foreach ($fields as $field) {
1211 $row[$field] = $dao->$field;
1214 $search->alterRow($row);
1219 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1220 CRM_Utils_System
::civiExit();
1223 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1224 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1228 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1229 if ($fieldName == 'id') {
1230 $fieldName = 'civicrm_primary_id';
1233 // early exit for master_id, CRM-12100
1234 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1235 if ($fieldName == 'master_id') {
1236 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1240 // set the sql columns
1241 if (isset($query->_fields
[$field]['type'])) {
1242 switch ($query->_fields
[$field]['type']) {
1243 case CRM_Utils_Type
::T_INT
:
1244 case CRM_Utils_Type
::T_BOOLEAN
:
1245 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1248 case CRM_Utils_Type
::T_STRING
:
1249 if (isset($query->_fields
[$field]['maxlength'])) {
1250 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1253 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1257 case CRM_Utils_Type
::T_TEXT
:
1258 case CRM_Utils_Type
::T_LONGTEXT
:
1259 case CRM_Utils_Type
::T_BLOB
:
1260 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1261 $sqlColumns[$fieldName] = "$fieldName longtext";
1264 case CRM_Utils_Type
::T_FLOAT
:
1265 case CRM_Utils_Type
::T_ENUM
:
1266 case CRM_Utils_Type
::T_DATE
:
1267 case CRM_Utils_Type
::T_TIME
:
1268 case CRM_Utils_Type
::T_TIMESTAMP
:
1269 case CRM_Utils_Type
::T_MONEY
:
1270 case CRM_Utils_Type
::T_EMAIL
:
1271 case CRM_Utils_Type
::T_URL
:
1272 case CRM_Utils_Type
::T_CCNUM
:
1274 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1279 if (substr($fieldName, -3, 3) == '_id') {
1280 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1283 $changeFields = array(
1289 if (in_array($fieldName, $changeFields)) {
1290 $sqlColumns[$fieldName] = "$fieldName text";
1293 // set the sql columns for custom data
1294 if (isset($query->_fields
[$field]['data_type'])) {
1296 switch ($query->_fields
[$field]['data_type']) {
1298 case 'StateProvince':
1301 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1305 $sqlColumns[$fieldName] = "$fieldName text";
1309 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1314 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1321 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1322 if (empty($details)) {
1331 $id = CRM_Core_DAO
::singleValueQuery($sql);
1336 $sqlClause = array();
1338 foreach ($details as $dontCare => $row) {
1340 $valueString = array($id);
1341 foreach ($row as $dontCare => $value) {
1342 if (empty($value)) {
1343 $valueString[] = "''";
1346 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1349 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1352 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1354 $sqlValueString = implode(",\n", $sqlClause);
1357 INSERT INTO $tableName $sqlColumnString
1358 VALUES $sqlValueString
1361 CRM_Core_DAO
::executeQuery($sql);
1364 static function createTempTable(&$sqlColumns) {
1365 //creating a temporary table for the search result that need be exported
1366 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1368 // also create the sql table
1369 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1370 CRM_Core_DAO
::executeQuery($sql);
1373 CREATE TABLE {$exportTempTable} (
1374 id int unsigned NOT NULL AUTO_INCREMENT,
1376 $sql .= implode(",\n", array_values($sqlColumns));
1381 // add indexes for street_address and household_name if present
1382 $addIndices = array(
1385 'civicrm_primary_id',
1388 foreach ($addIndices as $index) {
1389 if (isset($sqlColumns[$index])) {
1391 INDEX index_{$index}( $index )
1397 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1400 CRM_Core_DAO
::executeQuery($sql);
1401 return $exportTempTable;
1404 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1405 // check if any records are present based on if they have used shared address feature,
1406 // and not based on if city / state .. matches.
1408 SELECT r1.id as copy_id,
1409 r1.civicrm_primary_id as copy_contact_id,
1410 r1.addressee as copy_addressee,
1411 r1.addressee_id as copy_addressee_id,
1412 r1.postal_greeting as copy_postal_greeting,
1413 r1.postal_greeting_id as copy_postal_greeting_id,
1415 r2.civicrm_primary_id as master_contact_id,
1416 r2.postal_greeting as master_postal_greeting,
1417 r2.postal_greeting_id as master_postal_greeting_id,
1418 r2.addressee as master_addressee,
1419 r2.addressee_id as master_addressee_id
1421 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1422 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1424 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1426 // find all the records that have the same street address BUT not in a household
1427 // require match on city and state as well
1429 SELECT r1.id as master_id,
1430 r1.civicrm_primary_id as master_contact_id,
1431 r1.postal_greeting as master_postal_greeting,
1432 r1.postal_greeting_id as master_postal_greeting_id,
1433 r1.addressee as master_addressee,
1434 r1.addressee_id as master_addressee_id,
1436 r2.civicrm_primary_id as copy_contact_id,
1437 r2.postal_greeting as copy_postal_greeting,
1438 r2.postal_greeting_id as copy_postal_greeting_id,
1439 r2.addressee as copy_addressee,
1440 r2.addressee_id as copy_addressee_id
1442 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1443 r1.city = r2.city AND
1444 r1.state_province_id = r2.state_province_id )
1445 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1446 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1447 AND ( r1.street_address != '' )
1451 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1453 // unset ids from $merge already present in $linkedMerge
1454 foreach ($linkedMerge as $masterID => $values) {
1455 $keys = array($masterID);
1456 $keys = array_merge($keys, array_keys($values['copy']));
1457 foreach ($merge as $mid => $vals) {
1458 if (in_array($mid, $keys)) {
1459 unset($merge[$mid]);
1462 foreach ($values['copy'] as $copyId) {
1463 if (in_array($copyId, $keys)) {
1464 unset($merge[$mid]['copy'][$copyId]);
1470 $merge = $merge +
$linkedMerge;
1472 foreach ($merge as $masterID => $values) {
1475 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1478 $params = array(1 => array($values['addressee'], 'String'),
1479 2 => array($values['postalGreeting'], 'String'),
1480 3 => array($values['emailGreeting'], 'String'),
1481 4 => array($masterID, 'Integer'),
1483 CRM_Core_DAO
::executeQuery($sql, $params);
1485 // delete all copies
1486 $deleteIDs = array_keys($values['copy']);
1487 $deleteIDString = implode(',', $deleteIDs);
1489 DELETE FROM $tableName
1490 WHERE id IN ( $deleteIDString )
1492 CRM_Core_DAO
::executeQuery($sql);
1495 // unset temporary columns that were added for postal mailing format
1496 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1497 $unsetKeys = array_keys($sqlColumns);
1498 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1499 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1500 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1506 static function _replaceMergeTokens($contactId, $exportParams) {
1507 $greetings = array();
1510 $greetingFields = array(
1514 foreach ($greetingFields as $greeting) {
1515 if (CRM_Utils_Array
::value($greeting, $exportParams)) {
1516 $greetingLabel = $exportParams[$greeting];
1517 if (empty($contact)) {
1522 $contact = civicrm_api('contact', 'get', $values);
1524 if (CRM_Utils_Array
::value('is_error', $contact)) {
1527 $contact = $contact['values'][$contact['id']];
1530 $tokens = array('contact' => $greetingLabel);
1531 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1538 * The function unsets static part of the string, if token is the dynamic part.
1539 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1540 * i.e 'Hello Alan' => converted to => 'Alan'
1543 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1544 $addressMergeGreetings, $greetingType = 'postal_greeting'
1546 if (CRM_Utils_Array
::value($greetingType, $addressMergeGreetings)) {
1547 $greetingLabel = $addressMergeGreetings[$greetingType];
1549 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1551 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1552 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1553 foreach ($stringsToBeReplaced as $key => $string) {
1554 // to keep one space
1555 $stringsToBeReplaced[$key] = ltrim($string);
1557 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1559 return $parsedString;
1562 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1563 static $contactGreetingTokens = array();
1565 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1566 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1568 $merge = $parents = array();
1569 $dao = CRM_Core_DAO
::executeQuery($sql);
1571 while ($dao->fetch()) {
1572 $masterID = $dao->master_id
;
1573 $copyID = $dao->copy_id
;
1574 $masterPostalGreeting = $dao->master_postal_greeting
;
1575 $masterAddressee = $dao->master_addressee
;
1576 $copyAddressee = $dao->copy_addressee
;
1578 if (!$sharedAddress) {
1579 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1580 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1582 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1583 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1585 $masterAddressee = CRM_Utils_Array
::value('addressee',
1586 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1589 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1590 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1592 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1593 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1595 $copyAddressee = CRM_Utils_Array
::value('addressee',
1596 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1600 if (!isset($merge[$masterID])) {
1601 // check if this is an intermediate child
1602 // this happens if there are 3 or more matches a,b, c
1603 // the above query will return a, b / a, c / b, c
1604 // we might be doing a bit more work, but for now its ok, unless someone
1605 // knows how to fix the query above
1606 if (isset($parents[$masterID])) {
1607 $masterID = $parents[$masterID];
1610 $merge[$masterID] = array(
1611 'addressee' => $masterAddressee,
1613 'postalGreeting' => $masterPostalGreeting,
1615 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1618 $parents[$copyID] = $masterID;
1620 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1622 if (CRM_Utils_Array
::value('postal_greeting_other', $exportParams) &&
1623 count($merge[$masterID]['copy']) >= 1
1625 // use static greetings specified if no of contacts > 2
1626 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1628 elseif ($copyPostalGreeting) {
1629 self
::_trimNonTokens($copyPostalGreeting,
1630 $postalOptions[$dao->copy_postal_greeting_id
],
1633 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1634 // if there happens to be a duplicate, remove it
1635 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1638 if (CRM_Utils_Array
::value('addressee_other', $exportParams) &&
1639 count($merge[$masterID]['copy']) >= 1
1641 // use static greetings specified if no of contacts > 2
1642 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1644 elseif ($copyAddressee) {
1645 self
::_trimNonTokens($copyAddressee,
1646 $addresseeOptions[$dao->copy_addressee_id
],
1647 $exportParams, 'addressee'
1649 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1652 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1659 * Function to merge household record into the individual record
1662 * @param string $exportTempTable temporary temp table that stores the records
1663 * @param array $headerRows array of headers for the export file
1664 * @param array $sqlColumns array of names of the table columns of the temp table
1665 * @param string $prefix name of the relationship type that is prefixed to the table columns
1667 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1668 $prefixColumn = $prefix . '_';
1669 $allKeys = array_keys($sqlColumns);
1670 $replaced = array();
1671 $headerRows = array_values($headerRows);
1673 // name map of the non standard fields in header rows & sql columns
1674 $mappingFields = array(
1675 'civicrm_primary_id' => 'id',
1676 'contact_source' => 'source',
1677 'current_employer_id' => 'employer_id',
1678 'contact_is_deleted' => 'is_deleted',
1679 'name' => 'address_name',
1680 'provider_id' => 'im_service_provider',
1681 'phone_type_id' => 'phone_type'
1684 //figure out which columns are to be replaced by which ones
1685 foreach ($sqlColumns as $columnNames => $dontCare) {
1686 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1687 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1690 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1692 if (CRM_Utils_Array
::value($householdColName, $sqlColumns)) {
1693 $replaced[$columnNames] = $householdColName;
1697 $query = "UPDATE $exportTempTable SET ";
1700 foreach ($replaced as $from => $to) {
1701 $clause[] = "$from = $to ";
1702 unset($sqlColumns[$to]);
1703 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1704 unset($headerRows[$key]);
1707 $query .= implode(",\n", $clause);
1708 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1710 CRM_Core_DAO
::executeQuery($query);
1712 //drop the table columns that store redundant household info
1713 $dropQuery = "ALTER TABLE $exportTempTable ";
1714 foreach ($replaced as $householdColumns) {
1715 $dropClause[] = " DROP $householdColumns ";
1717 $dropQuery .= implode(",\n", $dropClause);
1719 CRM_Core_DAO
::executeQuery($dropQuery);
1721 // also drop the temp table if exists
1722 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1723 CRM_Core_DAO
::executeQuery($sql);
1725 // clean up duplicate records
1727 CREATE TABLE {$exportTempTable}_temp SELECT *
1728 FROM {$exportTempTable}
1729 GROUP BY civicrm_primary_id ";
1731 CRM_Core_DAO
::executeQuery($query);
1733 $query = "DROP TABLE $exportTempTable";
1734 CRM_Core_DAO
::executeQuery($query);
1736 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1737 CRM_Core_DAO
::executeQuery($query);
1740 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1741 $writeHeader = TRUE;
1743 $limit = self
::EXPORT_ROW_COUNT
;
1745 $query = "SELECT * FROM $exportTempTable";
1748 $limitQuery = $query . "
1749 LIMIT $offset, $limit
1751 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1757 $componentDetails = array();
1758 while ($dao->fetch()) {
1761 foreach ($sqlColumns as $column => $dontCare) {
1762 $row[$column] = $dao->$column;
1764 $componentDetails[] = $row;
1766 if ( $exportMode == 'financial' ) {
1767 $getExportFileName = 'CiviCRM Contribution Search';
1770 $getExportFileName =self
::getExportFileName( 'csv', $exportMode );
1772 $csvRows = CRM_Core_Report_Excel
::writeCSVFile( $getExportFileName,
1779 if ($saveFile && !empty($csvRows)) {
1780 $batchItems .= $csvRows;
1783 $writeHeader = false;
1789 * Function to manipulate header rows for relationship fields
1792 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1793 foreach ($headerRows as & $header) {
1794 $split = explode('-', $header);
1795 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1796 $split[0] = $relationTypeName;
1797 $header = implode('-', $split);
1803 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1804 * or have no street address
1807 function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1808 $whereClause = array();
1810 if (array_key_exists('is_deceased', $sqlColumns)) {
1811 $whereClause[] = 'is_deceased = 1';
1814 if (array_key_exists('do_not_mail', $sqlColumns)) {
1815 $whereClause[] = 'do_not_mail = 1';
1818 if (array_key_exists('street_address', $sqlColumns)) {
1819 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1821 // check for supplemental_address_1
1822 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1823 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1824 'address_options', TRUE, NULL, TRUE
1826 if (CRM_Utils_Array
::value('supplemental_address_1', $addressOptions)) {
1827 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1828 // enclose it again, since we are doing an AND in between a set of ORs
1829 $addressWhereClause = "( $addressWhereClause )";
1833 $whereClause[] = $addressWhereClause;
1836 if (!empty($whereClause)) {
1837 $whereClause = implode(' OR ', $whereClause);
1840 FROM $exportTempTable
1841 WHERE {$whereClause}";
1842 CRM_Core_DAO
::singleValueQuery($query);
1845 // unset temporary columns that were added for postal mailing format
1846 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1847 $unsetKeys = array_keys($sqlColumns);
1848 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1849 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1850 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1857 * Build componentPayment fields.
1859 static function componentPaymentFields() {
1860 static $componentPaymentFields;
1861 if (!isset( $componentPaymentFields)) {
1862 $componentPaymentFields = array(
1863 'componentPaymentField_total_amount' => ts('Total Amount'),
1864 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1865 'componentPaymentField_received_date' => ts('Received Date'),
1866 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1867 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1870 return $componentPaymentFields;