3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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
::phoneType();
87 $imProviders = CRM_Core_PseudoConstant
::IMProvider();
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
::locationType();
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 ($componentTable &&
374 CRM_Utils_Array
::value('additional_group', $exportParams)
376 // If an Additional Group is selected, then all contacts in that group are
377 // added to the export set (filtering out duplicates).
379 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";
380 CRM_Core_DAO
::executeQuery($query);
383 if ($moreReturnProperties) {
385 if (CRM_Utils_Array
::value('group', $moreReturnProperties)) {
386 unset($moreReturnProperties['group']);
387 $moreReturnProperties['groups'] = 1;
389 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
392 $exportParams['postal_mailing_export']['temp_columns'] = array();
393 if ($exportParams['exportOption'] == 2 &&
394 isset($exportParams['postal_mailing_export']) &&
395 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
397 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
398 foreach ($postalColumns as $column) {
399 if (!array_key_exists($column, $returnProperties)) {
400 $returnProperties[$column] = 1;
401 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
406 $query = new CRM_Contact_BAO_Query(NULL, $returnProperties, NULL,
407 FALSE, FALSE, $queryMode,
408 FALSE, TRUE, TRUE, NULL, $queryOperator
411 list($select, $from, $where, $having) = $query->query();
413 if ($mergeSameHousehold == 1) {
414 if (!$returnProperties['id']) {
415 $returnProperties['id'] = 1;
418 //also merge Head of Household
419 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
420 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
422 foreach ($returnProperties as $key => $value) {
423 if (!array_key_exists($key, $contactRelationshipTypes)) {
424 $returnProperties[$relationKeyMOH][$key] = $value;
425 $returnProperties[$relationKeyHOH][$key] = $value;
429 unset($returnProperties[$relationKeyMOH]['location_type']);
430 unset($returnProperties[$relationKeyMOH]['im_provider']);
431 unset($returnProperties[$relationKeyHOH]['location_type']);
432 unset($returnProperties[$relationKeyHOH]['im_provider']);
435 $allRelContactArray = $relationQuery = array();
437 foreach ($contactRelationshipTypes as $rel => $dnt) {
438 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
439 $allRelContactArray[$rel] = array();
440 // build Query for each relationship
441 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
442 NULL, FALSE, FALSE, $queryMode
444 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
446 list($id, $direction) = explode('_', $rel, 2);
447 // identify the relationship direction
448 $contactA = 'contact_id_a';
449 $contactB = 'contact_id_b';
450 if ($direction == 'b_a') {
451 $contactA = 'contact_id_b';
452 $contactB = 'contact_id_a';
454 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
457 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
458 $query = "SELECT source_contact_id FROM civicrm_activity
459 WHERE id IN ( " . implode(',', $ids) . ")";
460 $dao = CRM_Core_DAO
::executeQuery($query);
461 while ($dao->fetch()) {
462 $relIDs[] = $dao->source_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
::CASE_EXPORT
:
484 $component = 'civicrm_case';
487 case CRM_Export_Form_Select
::GRANT_EXPORT
:
488 $component = 'civicrm_grant';
491 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
494 $relationshipJoin = $relationshipClause = '';
495 if ($componentTable) {
496 $relationshipJoin = " INNER JOIN $componentTable ctTable ON ctTable.contact_id = {$contactA}";
499 $relID = implode(',', $relIDs);
500 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
503 $relationFrom = " {$relationFrom}
504 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
505 {$relationshipJoin} ";
507 //check for active relationship status only
508 $today = date('Ymd');
509 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
510 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
511 $relationGroupBy = " GROUP BY crel.{$contactA}";
512 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
513 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
515 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
516 while ($allRelContactDAO->fetch()) {
517 //FIX Me: Migrate this to table rather than array
518 // build the array of all related contacts
519 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
521 $allRelContactDAO->free();
525 // make sure the groups stuff is included only if specifically specified
526 // by the fields param (CRM-1969), else we limit the contacts outputted to only
527 // ones that are part of a group
528 if (CRM_Utils_Array
::value('groups', $returnProperties)) {
529 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
530 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
531 // total hack for export, CRM-3618
532 $from = str_replace($oldClause,
538 if ($componentTable) {
539 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
541 elseif ($componentClause) {
543 $where = "WHERE $componentClause";
546 $where .= " AND $componentClause";
550 $queryString = "$select $from $where $having";
553 if (CRM_Utils_Array
::value('tags', $returnProperties) ||
554 CRM_Utils_Array
::value('groups', $returnProperties) ||
555 CRM_Utils_Array
::value('notes', $returnProperties) ||
557 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
559 $groupBy = " GROUP BY contact_a.id";
562 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
563 $groupBy = " GROUP BY civicrm_activity.id ";
565 $queryString .= $groupBy;
567 list($field, $dir) = explode(' ', $order, 2);
568 $field = trim($field);
569 if (CRM_Utils_Array
::value($field, $returnProperties)) {
570 // $queryString .= " ORDER BY $order";
574 $multipleSelectFields = array('preferred_communication_method' => 1);
576 $addPaymentHeader = FALSE;
578 $paymentDetails = array();
579 if ($paymentFields ||
$selectedPaymentFields) {
581 // get payment related in for event and members
582 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
583 //get all payment headers.
584 if (!$selectedPaymentFields) {
585 $paymentHeaders = self
::componentPaymentFields();
586 if (!empty($paymentDetails)) {
587 $addPaymentHeader = TRUE;
590 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
594 if ($exportCampaign) {
595 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
598 $componentDetails = $headerRows = $sqlColumns = array();
601 $rowCount = self
::EXPORT_ROW_COUNT
;
603 // we write to temp table often to avoid using too much memory
608 // for CRM-3157 purposes
609 $i18n = CRM_Core_I18n
::singleton();
612 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
613 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
618 while ($dao->fetch()) {
622 //first loop through returnproperties so that we return what is required, and in same order.
623 $relationshipField = 0;
624 foreach ($returnProperties as $field => $value) {
625 //we should set header only once
628 if (isset($query->_fields
[$field]['title'])) {
629 $headerRows[] = $query->_fields
[$field]['title'];
631 elseif ($field == 'phone_type_id') {
632 $headerRows[] = ts('Phone Type');
634 elseif ($field == 'provider_id') {
635 $headerRows[] = ts('IM Service Provider');
637 elseif (is_array($value) && $field == 'location') {
638 // fix header for location type case
639 foreach ($value as $ltype => $val) {
640 foreach (array_keys($val) as $fld) {
641 $type = explode('-', $fld);
642 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
644 if (CRM_Utils_Array
::value(1, $type)) {
645 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
646 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
648 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
649 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
652 $headerRows[] = $hdr;
653 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
658 elseif (substr($field, 0, 5) == 'case_') {
659 if ($query->_fields
['case'][$field]['title']) {
660 $headerRows[] = $query->_fields
['case'][$field]['title'];
662 elseif ($query->_fields
['activity'][$field]['title']) {
663 $headerRows[] = $query->_fields
['activity'][$field]['title'];
666 elseif (array_key_exists($field, $contactRelationshipTypes)) {
668 foreach ($value as $relationField => $relationValue) {
669 // below block is same as primary block (duplicate)
670 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
671 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
672 $headerName = $field . '-' . $relationField;
675 if ($relationField == 'current_employer') {
676 $headerName = $field . '-' . 'current_employer';
679 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
683 $headerRows[] = $headerName;
685 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
687 elseif ($relationField == 'phone_type_id') {
688 $headerName = $field . '-' . 'Phone Type';
689 $headerRows[] = $headerName;
690 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
692 elseif ($relationField == 'provider_id') {
693 $headerName = $field . '-' . 'Im Service Provider';
694 $headerRows[] = $headerName;
695 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
697 elseif ($relationField == 'state_province_id') {
698 $headerName = $field . '-' . 'state_province_id';
699 $headerRows[] = $headerName;
700 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
702 elseif (is_array($relationValue) && $relationField == 'location') {
703 // fix header for location type case
704 foreach ($relationValue as $ltype => $val) {
705 foreach (array_keys($val) as $fld) {
706 $type = explode('-', $fld);
708 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
710 if (CRM_Utils_Array
::value(1, $type)) {
711 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
712 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
714 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
715 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
718 $headerName = $field . '-' . $hdr;
719 $headerRows[] = $headerName;
720 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
726 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
727 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
730 $headerRows[] = $field;
734 self
::sqlColumnDefn($query, $sqlColumns, $field);
738 // add im_provider to $dao object
739 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
740 $dao->im_provider
= $dao->provider_id
;
743 //build row values (data)
745 if (property_exists($dao, $field)) {
746 $fieldValue = $dao->$field;
747 // to get phone type from phone type id
748 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
749 $fieldValue = $phoneTypes[$fieldValue];
751 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
752 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
754 elseif ($field == 'participant_role_id') {
755 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
756 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
757 $viewRoles = array();
758 foreach (explode($sep, $dao->$field) as $k => $v) {
759 $viewRoles[] = $participantRoles[$v];
761 $fieldValue = implode(',', $viewRoles);
763 elseif ($field == 'master_id') {
764 $masterAddressId = NULL;
765 if (isset($dao->master_id
)) {
766 $masterAddressId = $dao->master_id
;
768 // get display name of contact that address is shared.
769 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $dao->contact_id
);
773 if ($field == 'id') {
774 $row[$field] = $dao->contact_id
;
775 // special case for calculated field
777 elseif ($field == 'pledge_balance_amount') {
778 $row[$field] = $dao->pledge_amount
- $dao->pledge_total_paid
;
779 // special case for calculated field
781 elseif ($field == 'pledge_next_pay_amount') {
782 $row[$field] = $dao->pledge_next_pay_amount +
$dao->pledge_outstanding_amount
;
784 elseif (is_array($value) && $field == 'location') {
785 // fix header for location type case
786 foreach ($value as $ltype => $val) {
787 foreach (array_keys($val) as $fld) {
788 $type = explode('-', $fld);
789 $fldValue = "{$ltype}-" . $type[0];
791 if (CRM_Utils_Array
::value(1, $type)) {
792 $fldValue .= "-" . $type[1];
795 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
799 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'country'));
802 case 'state_province':
803 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'province'));
807 $imFieldvalue = $fldValue . "-provider_id";
808 $row[$fldValue] = CRM_Utils_Array
::value($dao->$imFieldvalue, $imProviders);
812 $row[$fldValue] = $dao->$fldValue;
818 elseif (array_key_exists($field, $contactRelationshipTypes)) {
819 $relDAO = CRM_Utils_Array
::value($dao->contact_id
, $allRelContactArray[$field]);
820 foreach ($value as $relationField => $relationValue) {
821 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
822 $fieldValue = $relDAO->$relationField;
823 if ($relationField == 'phone_type_id') {
824 $fieldValue = $phoneTypes[$relationValue];
826 elseif ($relationField == 'provider_id') {
827 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
833 $field = $field . '_';
834 if (is_object($relDAO) && $relationField == 'id') {
835 $row[$field . $relationField] = $relDAO->contact_id
;
836 } else if ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
837 foreach ($relationValue as $ltype => $val) {
838 foreach (array_keys($val) as $fld) {
839 $type = explode('-', $fld);
840 $fldValue = "{$ltype}-" . $type[0];
841 if (CRM_Utils_Array
::value(1, $type)) {
842 $fldValue .= "-" . $type[1];
844 // CRM-3157: localise country, region (both have ‘country’ context)
845 // and state_province (‘province’ context)
847 case (!is_object($relDAO)):
848 $row[$field . '_' . $fldValue] = '';
851 case in_array('country', $type):
852 case in_array('world_region', $type):
853 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
854 array('context' => 'country')
858 case in_array('state_province', $type):
859 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
860 array('context' => 'province')
865 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
871 elseif (isset($fieldValue) && $fieldValue != '') {
872 //check for custom data
873 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
874 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
875 $relationQuery[$field]->_options
878 elseif (in_array($relationField, array(
879 'email_greeting', 'postal_greeting', 'addressee'))) {
880 //special case for greeting replacement
881 $fldValue = "{$relationField}_display";
882 $row[$field . $relationField] = $relDAO->$fldValue;
885 //normal relationship fields
886 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
887 switch ($relationField) {
890 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
893 case 'state_province':
894 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
898 $row[$field . $relationField] = $fieldValue;
904 // if relation field is empty or null
905 $row[$field . $relationField] = '';
909 elseif (isset($fieldValue) &&
912 //check for custom data
913 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
914 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
916 elseif (array_key_exists($field, $multipleSelectFields)) {
918 $paramsNew = array($field => $fieldValue);
919 if ($field == 'test_tutoring') {
920 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
923 elseif (substr($field, 0, 4) == 'cmr_') {
924 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
927 $name = array($field => array('newName' => $field, 'groupName' => $field));
929 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
930 $row[$field] = $paramsNew[$field];
932 elseif (in_array($field, array(
933 'email_greeting', 'postal_greeting', 'addressee'))) {
934 //special case for greeting replacement
935 $fldValue = "{$field}_display";
936 $row[$field] = $dao->$fldValue;
939 //normal fields with a touch of CRM-3157
943 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
946 case 'state_province':
947 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
951 case 'preferred_communication_method':
952 case 'preferred_mail_format':
953 $row[$field] = $i18n->crm_translate($fieldValue);
957 $row[$field] = $fieldValue;
962 elseif (substr($field, -8) == 'campaign') {
963 $campIdFld = "{$field}_id";
964 $row[$field] = CRM_Utils_Array
::value($dao->$campIdFld, $allCampaigns, '');
966 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
967 $paymentData = CRM_Utils_Array
::value($dao->$paymentTableId, $paymentDetails);
968 $payFieldMapper = array(
969 'componentPaymentField_total_amount' => 'total_amount',
970 'componentPaymentField_contribution_status' => 'contribution_status',
971 'componentPaymentField_payment_instrument' => 'pay_instru',
972 'componentPaymentField_transaction_id' => 'trxn_id',
973 'componentPaymentField_received_date' => 'receive_date',
975 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
978 // if field is empty or null
983 // add payment headers if required
984 if ($addPaymentHeader && $paymentFields) {
985 $headerRows = array_merge($headerRows, $paymentHeaders);
986 foreach (array_keys($paymentHeaders) as $paymentHdr) {
987 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
989 $addPaymentHeader = FALSE;
993 $exportTempTable = self
::createTempTable($sqlColumns);
996 //build header only once
999 // If specific payment fields have been selected for export, payment
1000 // data will already be in $row. Otherwise, add payment related
1001 // information, if appropriate.
1002 if (!$selectedPaymentFields) {
1003 if ($paymentFields) {
1004 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1005 if (!is_array($paymentData) ||
empty($paymentData)) {
1006 $paymentData = $nullContributionDetails;
1008 $row = array_merge($row, $paymentData);
1010 elseif (!empty($paymentDetails)) {
1011 $row = array_merge($row, $nullContributionDetails);
1015 //remove organization name for individuals if it is set for current employer
1016 if (CRM_Utils_Array
::value('contact_type', $row) &&
1017 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1019 $row['organization_name'] = '';
1022 // add component info
1023 // write the row to a file
1024 $componentDetails[] = $row;
1026 // output every $tempRowCount rows
1027 if ($count %
$tempRowCount == 0) {
1028 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1029 $componentDetails = array();
1033 $offset +
= $rowCount;
1036 if ($exportTempTable) {
1037 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1039 // do merge same address and merge same household processing
1040 if ($mergeSameAddress) {
1041 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1044 // merge the records if they have corresponding households
1045 if ($mergeSameHousehold) {
1046 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1047 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1050 // fix the headers for rows with relationship type
1051 if (!empty($relName)) {
1052 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1055 // if postalMailing option is checked, exclude contacts who are deceased, have
1056 // "Do not mail" privacy setting, or have no street address
1057 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1058 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1060 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1064 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1066 // now write the CSV file
1067 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1069 // delete the export temp table and component table
1070 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1071 CRM_Core_DAO
::executeQuery($sql);
1073 CRM_Utils_System
::civiExit();
1076 CRM_Core_Error
::fatal(ts('No records to export'));
1081 * name of the export file based on mode
1083 * @param string $output type of output
1084 * @param int $mode export mode
1086 * @return string name of the file
1088 function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1090 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1091 return ts('CiviCRM Contact Search');
1093 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1094 return ts('CiviCRM Contribution Search');
1096 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1097 return ts('CiviCRM Member Search');
1099 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1100 return ts('CiviCRM Participant Search');
1102 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1103 return ts('CiviCRM Pledge Search');
1105 case CRM_Export_Form_Select
::CASE_EXPORT
:
1106 return ts('CiviCRM Case Search');
1108 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1109 return ts('CiviCRM Grant Search');
1111 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1112 return ts('CiviCRM Activity Search');
1117 * Function to handle import error file creation.
1121 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1122 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1123 if (empty($parserName) ||
empty($type)) {
1127 // clean and ensure parserName is a valid string
1128 $parserName = CRM_Utils_String
::munge($parserName);
1129 $parserClass = explode('_', $parserName);
1131 // make sure parserClass is in the CRM namespace and
1132 // at least 3 levels deep
1133 if ($parserClass[0] == 'CRM' &&
1134 count($parserClass) >= 3
1136 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php");
1137 // ensure the functions exists
1138 if (method_exists($parserName, 'errorFileName') &&
1139 method_exists($parserName, 'saveFileName')
1141 $errorFileName = $parserName::errorFileName($type);
1142 $saveFileName = $parserName::saveFileName($type);
1143 if (!empty($errorFileName) && !empty($saveFileName)) {
1144 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1145 header('Content-Description: File Transfer');
1146 header('Content-Type: text/csv');
1147 header('Content-Length: ' . filesize($errorFileName));
1148 header('Content-Disposition: attachment; filename=' . $saveFileName);
1150 readfile($errorFileName);
1154 CRM_Utils_System
::civiExit();
1157 function exportCustom($customSearchClass, $formValues, $order) {
1158 $ext = CRM_Extension_System
::singleton()->getMapper();
1159 if (!$ext->isExtensionClass($customSearchClass)) {
1160 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php');
1163 require_once ($ext->classToPath($customSearchClass));
1165 $search = new $customSearchClass($formValues);
1167 $includeContactIDs = FALSE;
1168 if ($formValues['radio_ts'] == 'ts_sel') {
1169 $includeContactIDs = TRUE;
1172 $sql = $search->all(0, 0, $order, $includeContactIDs);
1174 $columns = $search->columns();
1176 $header = array_keys($columns);
1177 $fields = array_values($columns);
1180 $dao = CRM_Core_DAO
::executeQuery($sql);
1182 if (method_exists($search, 'alterRow')) {
1185 while ($dao->fetch()) {
1188 foreach ($fields as $field) {
1189 $row[$field] = $dao->$field;
1192 $search->alterRow($row);
1197 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1198 CRM_Utils_System
::civiExit();
1201 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1202 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1206 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1207 if ($fieldName == 'id') {
1208 $fieldName = 'civicrm_primary_id';
1211 // early exit for master_id, CRM-12100
1212 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1213 if ($fieldName == 'master_id') {
1214 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1218 // set the sql columns
1219 if (isset($query->_fields
[$field]['type'])) {
1220 switch ($query->_fields
[$field]['type']) {
1221 case CRM_Utils_Type
::T_INT
:
1222 case CRM_Utils_Type
::T_BOOL
:
1223 case CRM_Utils_Type
::T_BOOLEAN
:
1224 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1227 case CRM_Utils_Type
::T_STRING
:
1228 if (isset($query->_fields
[$field]['maxlength'])) {
1229 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1232 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1236 case CRM_Utils_Type
::T_TEXT
:
1237 case CRM_Utils_Type
::T_LONGTEXT
:
1238 case CRM_Utils_Type
::T_BLOB
:
1239 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1240 $sqlColumns[$fieldName] = "$fieldName longtext";
1243 case CRM_Utils_Type
::T_FLOAT
:
1244 case CRM_Utils_Type
::T_ENUM
:
1245 case CRM_Utils_Type
::T_DATE
:
1246 case CRM_Utils_Type
::T_TIME
:
1247 case CRM_Utils_Type
::T_TIMESTAMP
:
1248 case CRM_Utils_Type
::T_MONEY
:
1249 case CRM_Utils_Type
::T_EMAIL
:
1250 case CRM_Utils_Type
::T_URL
:
1251 case CRM_Utils_Type
::T_CCNUM
:
1253 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1258 if (substr($fieldName, -3, 3) == '_id') {
1259 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1262 $changeFields = array(
1268 if (in_array($fieldName, $changeFields)) {
1269 $sqlColumns[$fieldName] = "$fieldName text";
1272 // set the sql columns for custom data
1273 if (isset($query->_fields
[$field]['data_type'])) {
1275 switch ($query->_fields
[$field]['data_type']) {
1277 case 'StateProvince':
1280 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1284 $sqlColumns[$fieldName] = "$fieldName text";
1288 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1293 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1300 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1301 if (empty($details)) {
1310 $id = CRM_Core_DAO
::singleValueQuery($sql);
1315 $sqlClause = array();
1317 foreach ($details as $dontCare => $row) {
1319 $valueString = array($id);
1320 foreach ($row as $dontCare => $value) {
1321 if (empty($value)) {
1322 $valueString[] = "''";
1325 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1328 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1331 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1333 $sqlValueString = implode(",\n", $sqlClause);
1336 INSERT INTO $tableName $sqlColumnString
1337 VALUES $sqlValueString
1340 CRM_Core_DAO
::executeQuery($sql);
1343 static function createTempTable(&$sqlColumns) {
1344 //creating a temporary table for the search result that need be exported
1345 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1347 // also create the sql table
1348 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1349 CRM_Core_DAO
::executeQuery($sql);
1352 CREATE TABLE {$exportTempTable} (
1353 id int unsigned NOT NULL AUTO_INCREMENT,
1355 $sql .= implode(",\n", array_values($sqlColumns));
1360 // add indexes for street_address and household_name if present
1361 $addIndices = array(
1364 'civicrm_primary_id',
1367 foreach ($addIndices as $index) {
1368 if (isset($sqlColumns[$index])) {
1370 INDEX index_{$index}( $index )
1376 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1379 CRM_Core_DAO
::executeQuery($sql);
1380 return $exportTempTable;
1383 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1384 // check if any records are present based on if they have used shared address feature,
1385 // and not based on if city / state .. matches.
1387 SELECT r1.id as copy_id,
1388 r1.civicrm_primary_id as copy_contact_id,
1389 r1.addressee as copy_addressee,
1390 r1.addressee_id as copy_addressee_id,
1391 r1.postal_greeting as copy_postal_greeting,
1392 r1.postal_greeting_id as copy_postal_greeting_id,
1394 r2.civicrm_primary_id as master_contact_id,
1395 r2.postal_greeting as master_postal_greeting,
1396 r2.postal_greeting_id as master_postal_greeting_id,
1397 r2.addressee as master_addressee,
1398 r2.addressee_id as master_addressee_id
1400 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1401 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1403 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1405 // find all the records that have the same street address BUT not in a household
1406 // require match on city and state as well
1408 SELECT r1.id as master_id,
1409 r1.civicrm_primary_id as master_contact_id,
1410 r1.postal_greeting as master_postal_greeting,
1411 r1.postal_greeting_id as master_postal_greeting_id,
1412 r1.addressee as master_addressee,
1413 r1.addressee_id as master_addressee_id,
1415 r2.civicrm_primary_id as copy_contact_id,
1416 r2.postal_greeting as copy_postal_greeting,
1417 r2.postal_greeting_id as copy_postal_greeting_id,
1418 r2.addressee as copy_addressee,
1419 r2.addressee_id as copy_addressee_id
1421 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1422 r1.city = r2.city AND
1423 r1.state_province_id = r2.state_province_id )
1424 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1425 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1426 AND ( r1.street_address != '' )
1430 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1432 // unset ids from $merge already present in $linkedMerge
1433 foreach ($linkedMerge as $masterID => $values) {
1434 $keys = array($masterID);
1435 $keys = array_merge($keys, array_keys($values['copy']));
1436 foreach ($merge as $mid => $vals) {
1437 if (in_array($mid, $keys)) {
1438 unset($merge[$mid]);
1441 foreach ($values['copy'] as $copyId) {
1442 if (in_array($copyId, $keys)) {
1443 unset($merge[$mid]['copy'][$copyId]);
1449 $merge = $merge +
$linkedMerge;
1451 foreach ($merge as $masterID => $values) {
1454 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1457 $params = array(1 => array($values['addressee'], 'String'),
1458 2 => array($values['postalGreeting'], 'String'),
1459 3 => array($values['emailGreeting'], 'String'),
1460 4 => array($masterID, 'Integer'),
1462 CRM_Core_DAO
::executeQuery($sql, $params);
1464 // delete all copies
1465 $deleteIDs = array_keys($values['copy']);
1466 $deleteIDString = implode(',', $deleteIDs);
1468 DELETE FROM $tableName
1469 WHERE id IN ( $deleteIDString )
1471 CRM_Core_DAO
::executeQuery($sql);
1474 // unset temporary columns that were added for postal mailing format
1475 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1476 $unsetKeys = array_keys($sqlColumns);
1477 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1478 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1479 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1485 static function _replaceMergeTokens($contactId, $exportParams) {
1486 $greetings = array();
1489 $greetingFields = array(
1493 foreach ($greetingFields as $greeting) {
1494 if (CRM_Utils_Array
::value($greeting, $exportParams)) {
1495 $greetingLabel = $exportParams[$greeting];
1496 if (empty($contact)) {
1501 $contact = civicrm_api('contact', 'get', $values);
1503 if (CRM_Utils_Array
::value('is_error', $contact)) {
1506 $contact = $contact['values'][$contact['id']];
1509 $tokens = array('contact' => $greetingLabel);
1510 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1517 * The function unsets static part of the string, if token is the dynamic part.
1518 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1519 * i.e 'Hello Alan' => converted to => 'Alan'
1522 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1523 $addressMergeGreetings, $greetingType = 'postal_greeting'
1525 if (CRM_Utils_Array
::value($greetingType, $addressMergeGreetings)) {
1526 $greetingLabel = $addressMergeGreetings[$greetingType];
1528 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1530 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1531 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1532 foreach ($stringsToBeReplaced as $key => $string) {
1533 // to keep one space
1534 $stringsToBeReplaced[$key] = ltrim($string);
1536 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1538 return $parsedString;
1541 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1542 static $contactGreetingTokens = array();
1544 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1545 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1547 $merge = $parents = array();
1548 $dao = CRM_Core_DAO
::executeQuery($sql);
1550 while ($dao->fetch()) {
1551 $masterID = $dao->master_id
;
1552 $copyID = $dao->copy_id
;
1553 $masterPostalGreeting = $dao->master_postal_greeting
;
1554 $masterAddressee = $dao->master_addressee
;
1555 $copyAddressee = $dao->copy_addressee
;
1557 if (!$sharedAddress) {
1558 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1559 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1561 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1562 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1564 $masterAddressee = CRM_Utils_Array
::value('addressee',
1565 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1568 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1569 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1571 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1572 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1574 $copyAddressee = CRM_Utils_Array
::value('addressee',
1575 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1579 if (!isset($merge[$masterID])) {
1580 // check if this is an intermediate child
1581 // this happens if there are 3 or more matches a,b, c
1582 // the above query will return a, b / a, c / b, c
1583 // we might be doing a bit more work, but for now its ok, unless someone
1584 // knows how to fix the query above
1585 if (isset($parents[$masterID])) {
1586 $masterID = $parents[$masterID];
1589 $merge[$masterID] = array(
1590 'addressee' => $masterAddressee,
1592 'postalGreeting' => $masterPostalGreeting,
1594 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1597 $parents[$copyID] = $masterID;
1599 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1601 if (CRM_Utils_Array
::value('postal_greeting_other', $exportParams) &&
1602 count($merge[$masterID]['copy']) >= 1
1604 // use static greetings specified if no of contacts > 2
1605 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1607 elseif ($copyPostalGreeting) {
1608 self
::_trimNonTokens($copyPostalGreeting,
1609 $postalOptions[$dao->copy_postal_greeting_id
],
1612 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1613 // if there happens to be a duplicate, remove it
1614 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1617 if (CRM_Utils_Array
::value('addressee_other', $exportParams) &&
1618 count($merge[$masterID]['copy']) >= 1
1620 // use static greetings specified if no of contacts > 2
1621 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1623 elseif ($copyAddressee) {
1624 self
::_trimNonTokens($copyAddressee,
1625 $addresseeOptions[$dao->copy_addressee_id
],
1626 $exportParams, 'addressee'
1628 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1631 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1638 * Function to merge household record into the individual record
1641 * @param string $exportTempTable temporary temp table that stores the records
1642 * @param array $headerRows array of headers for the export file
1643 * @param array $sqlColumns array of names of the table columns of the temp table
1644 * @param string $prefix name of the relationship type that is prefixed to the table columns
1646 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1647 $prefixColumn = $prefix . '_';
1648 $allKeys = array_keys($sqlColumns);
1649 $replaced = array();
1650 $headerRows = array_values($headerRows);
1652 // name map of the non standard fields in header rows & sql columns
1653 $mappingFields = array(
1654 'civicrm_primary_id' => 'id',
1655 'contact_source' => 'source',
1656 'current_employer_id' => 'employer_id',
1657 'contact_is_deleted' => 'is_deleted',
1658 'name' => 'address_name',
1659 'provider_id' => 'im_service_provider',
1660 'phone_type_id' => 'phone_type'
1663 //figure out which columns are to be replaced by which ones
1664 foreach ($sqlColumns as $columnNames => $dontCare) {
1665 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1666 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1669 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1671 if (CRM_Utils_Array
::value($householdColName, $sqlColumns)) {
1672 $replaced[$columnNames] = $householdColName;
1676 $query = "UPDATE $exportTempTable SET ";
1679 foreach ($replaced as $from => $to) {
1680 $clause[] = "$from = $to ";
1681 unset($sqlColumns[$to]);
1682 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1683 unset($headerRows[$key]);
1686 $query .= implode(",\n", $clause);
1687 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1689 CRM_Core_DAO
::executeQuery($query);
1691 //drop the table columns that store redundant household info
1692 $dropQuery = "ALTER TABLE $exportTempTable ";
1693 foreach ($replaced as $householdColumns) {
1694 $dropClause[] = " DROP $householdColumns ";
1696 $dropQuery .= implode(",\n", $dropClause);
1698 CRM_Core_DAO
::executeQuery($dropQuery);
1700 // also drop the temp table if exists
1701 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1702 CRM_Core_DAO
::executeQuery($sql);
1704 // clean up duplicate records
1706 CREATE TABLE {$exportTempTable}_temp SELECT *
1707 FROM {$exportTempTable}
1708 GROUP BY civicrm_primary_id ";
1710 CRM_Core_DAO
::executeQuery($query);
1712 $query = "DROP TABLE $exportTempTable";
1713 CRM_Core_DAO
::executeQuery($query);
1715 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1716 CRM_Core_DAO
::executeQuery($query);
1719 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1720 $writeHeader = TRUE;
1722 $limit = self
::EXPORT_ROW_COUNT
;
1724 $query = "SELECT * FROM $exportTempTable";
1727 $limitQuery = $query . "
1728 LIMIT $offset, $limit
1730 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1736 $componentDetails = array();
1737 while ($dao->fetch()) {
1740 foreach ($sqlColumns as $column => $dontCare) {
1741 $row[$column] = $dao->$column;
1743 $componentDetails[] = $row;
1745 if ( $exportMode == 'financial' ) {
1746 $getExportFileName = 'CiviCRM Contribution Search';
1749 $getExportFileName =self
::getExportFileName( 'csv', $exportMode );
1751 $csvRows = CRM_Core_Report_Excel
::writeCSVFile( $getExportFileName,
1758 if ($saveFile && !empty($csvRows)) {
1759 $batchItems .= $csvRows;
1762 $writeHeader = false;
1768 * Function to manipulate header rows for relationship fields
1771 function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1772 foreach ($headerRows as & $header) {
1773 $split = explode('-', $header);
1774 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1775 $split[0] = $relationTypeName;
1776 $header = implode('-', $split);
1782 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1783 * or have no street address
1786 function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1787 $whereClause = array();
1789 if (array_key_exists('is_deceased', $sqlColumns)) {
1790 $whereClause[] = 'is_deceased = 1';
1793 if (array_key_exists('do_not_mail', $sqlColumns)) {
1794 $whereClause[] = 'do_not_mail = 1';
1797 if (array_key_exists('street_address', $sqlColumns)) {
1798 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1800 // check for supplemental_address_1
1801 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1802 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1803 'address_options', TRUE, NULL, TRUE
1805 if (CRM_Utils_Array
::value('supplemental_address_1', $addressOptions)) {
1806 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1807 // enclose it again, since we are doing an AND in between a set of ORs
1808 $addressWhereClause = "( $addressWhereClause )";
1812 $whereClause[] = $addressWhereClause;
1815 if (!empty($whereClause)) {
1816 $whereClause = implode(' OR ', $whereClause);
1819 FROM $exportTempTable
1820 WHERE {$whereClause}";
1821 CRM_Core_DAO
::singleValueQuery($query);
1824 // unset temporary columns that were added for postal mailing format
1825 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1826 $unsetKeys = array_keys($sqlColumns);
1827 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1828 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1829 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1836 * Build componentPayment fields.
1838 static function componentPaymentFields() {
1839 static $componentPaymentFields;
1840 if (!isset( $componentPaymentFields)) {
1841 $componentPaymentFields = array(
1842 'componentPaymentField_total_amount' => ts('Total Amount'),
1843 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1844 'componentPaymentField_received_date' => ts('Received Date'),
1845 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1846 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1849 return $componentPaymentFields;