3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class contains the funtions for Component export
40 class CRM_Export_BAO_Export
{
41 // increase this number a lot to avoid making too many queries
42 // LIMIT is not much faster than a no LIMIT query
44 CONST EXPORT_ROW_COUNT
= 10000;
47 * Function to get the list the export fields
49 * @param int $selectAll user preference while export
50 * @param array $ids contact ids
51 * @param array $params associated array of fields
52 * @param string $order order by clause
53 * @param array $fields associated array of fields
54 * @param array $moreReturnProperties additional return fields
55 * @param int $exportMode export mode
56 * @param string $componentClause component clause
57 * @param string $componentTable component table
58 * @param bool $mergeSameAddress merge records if they have same address
59 * @param bool $mergeSameHousehold merge records if they belong to the same household
64 static function exportComponents($selectAll,
69 $moreReturnProperties = NULL,
70 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
71 $componentClause = NULL,
72 $componentTable = NULL,
73 $mergeSameAddress = FALSE,
74 $mergeSameHousehold = FALSE,
75 $exportParams = array(),
76 $queryOperator = 'AND'
78 $headerRows = $returnProperties = array();
79 $primary = $paymentFields = $selectedPaymentFields = FALSE;
80 $origFields = $fields;
81 $queryMode = $relationField = NULL;
83 $allCampaigns = array();
85 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
86 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
87 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
96 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
98 switch ($exportMode) {
99 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
100 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
103 case CRM_Export_Form_Select
::EVENT_EXPORT
:
104 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
107 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
108 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
111 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
112 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
115 case CRM_Export_Form_Select
::CASE_EXPORT
:
116 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
119 case CRM_Export_Form_Select
::GRANT_EXPORT
:
120 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
123 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
124 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
128 //construct return properties
129 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
130 $locationTypeFields = array(
132 'supplemental_address_1',
133 'supplemental_address_2',
136 'postal_code_suffix',
146 foreach ($fields as $key => $value) {
147 $phoneTypeId = $imProviderId = NULL;
148 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
152 // get phoneType id and IM service provider id seperately
153 if ($fieldName == 'phone') {
154 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
156 elseif ($fieldName == 'im') {
157 $imProviderId = CRM_Utils_Array
::value(3, $value);
160 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
161 if (!empty($value[2])) {
162 $relationField = CRM_Utils_Array
::value(2, $value);
163 if (trim(CRM_Utils_Array
::value(3, $value))) {
164 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
167 $relLocTypeId = 'Primary';
170 if ($relationField == 'phone') {
171 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
173 elseif ($relationField == 'im') {
174 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
177 elseif (!empty($value[4])) {
178 $relationField = CRM_Utils_Array
::value(4, $value);
179 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
180 if ($relationField == 'phone') {
181 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
183 elseif ($relationField == 'im') {
184 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
189 $contactType = CRM_Utils_Array
::value(0, $value);
190 $locTypeId = CRM_Utils_Array
::value(2, $value);
192 if ($relationField) {
193 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
194 if ($relPhoneTypeId) {
195 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
197 elseif ($relIMProviderId) {
198 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
201 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
203 $relPhoneTypeId = $relIMProviderId = NULL;
206 $returnProperties[$relationshipTypes][$relationField] = 1;
209 elseif (is_numeric($locTypeId)) {
211 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
213 elseif ($imProviderId) {
214 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
217 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
221 //hack to fix component fields
222 if ($fieldName == 'event_id') {
223 $returnProperties['event_title'] = 1;
226 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
227 array_key_exists( $fieldName, self
::componentPaymentFields())
229 $selectedPaymentFields = true;
230 $paymentTableId = 'participant_id';
231 $returnProperties[$fieldName] = 1;
234 $returnProperties[$fieldName] = 1;
239 // hack to add default returnproperty based on export mode
240 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
241 $returnProperties['contribution_id'] = 1;
243 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
244 $returnProperties['participant_id'] = 1;
245 if (!empty($returnProperties['participant_role'])) {
246 unset($returnProperties['participant_role']);
247 $returnProperties['participant_role_id'] = 1;
250 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
251 $returnProperties['membership_id'] = 1;
253 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
254 $returnProperties['pledge_id'] = 1;
256 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
257 $returnProperties['case_id'] = 1;
259 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
260 $returnProperties['grant_id'] = 1;
262 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
263 $returnProperties['activity_id'] = 1;
268 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
269 foreach ($fields as $key => $var) {
270 if ($key && (substr($key, 0, 6) != 'custom')) {
272 $returnProperties[$key] = 1;
277 $returnProperties['location_type'] = 1;
278 $returnProperties['im_provider'] = 1;
279 $returnProperties['phone_type_id'] = 1;
280 $returnProperties['provider_id'] = 1;
281 $returnProperties['current_employer'] = 1;
284 $extraReturnProperties = array();
285 $paymentFields = FALSE;
287 switch ($queryMode) {
288 case CRM_Contact_BAO_Query
::MODE_EVENT
:
289 $paymentFields = TRUE;
290 $paymentTableId = 'participant_id';
293 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
294 $paymentFields = TRUE;
295 $paymentTableId = 'membership_id';
298 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
299 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
300 $paymentFields = TRUE;
301 $paymentTableId = 'pledge_payment_id';
304 case CRM_Contact_BAO_Query
::MODE_CASE
:
305 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
309 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
310 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
311 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
312 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
313 $componentReturnProperties =
315 $componentReturnProperties,
316 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
318 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
320 if (!empty($extraReturnProperties)) {
321 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
324 // unset non exportable fields for components
325 $nonExpoFields = array(
326 'groups', 'tags', 'notes', 'contribution_status_id',
327 'pledge_status_id', 'pledge_payment_status_id',
329 foreach ($nonExpoFields as $value) {
330 unset($returnProperties[$value]);
335 if ($mergeSameAddress) {
336 //make sure the addressee fields are selected
337 //while using merge same address feature
338 $returnProperties['addressee'] = 1;
339 $returnProperties['postal_greeting'] = 1;
340 $returnProperties['email_greeting'] = 1;
341 $returnProperties['street_name'] = 1;
342 $returnProperties['household_name'] = 1;
343 $returnProperties['street_address'] = 1;
344 $returnProperties['city'] = 1;
345 $returnProperties['state_province'] = 1;
347 // some columns are required for assistance incase they are not already present
348 $exportParams['merge_same_address']['temp_columns'] = array();
349 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
350 foreach ($tempColumns as $column) {
351 if (!array_key_exists($column, $returnProperties)) {
352 $returnProperties[$column] = 1;
353 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
354 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
359 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
360 // If an Additional Group is selected, then all contacts in that group are
361 // added to the export set (filtering out duplicates).
363 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";
364 CRM_Core_DAO
::executeQuery($query);
367 if ($moreReturnProperties) {
369 if (!empty($moreReturnProperties['group'])) {
370 unset($moreReturnProperties['group']);
371 $moreReturnProperties['groups'] = 1;
373 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
376 $exportParams['postal_mailing_export']['temp_columns'] = array();
377 if ($exportParams['exportOption'] == 2 &&
378 isset($exportParams['postal_mailing_export']) &&
379 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
381 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
382 foreach ($postalColumns as $column) {
383 if (!array_key_exists($column, $returnProperties)) {
384 $returnProperties[$column] = 1;
385 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
390 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
391 FALSE, FALSE, $queryMode,
392 FALSE, TRUE, TRUE, NULL, $queryOperator
395 list($select, $from, $where, $having) = $query->query();
397 if ($mergeSameHousehold == 1) {
398 if (!$returnProperties['id']) {
399 $returnProperties['id'] = 1;
402 //also merge Head of Household
403 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
404 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
406 foreach ($returnProperties as $key => $value) {
407 if (!array_key_exists($key, $contactRelationshipTypes)) {
408 $returnProperties[$relationKeyMOH][$key] = $value;
409 $returnProperties[$relationKeyHOH][$key] = $value;
413 unset($returnProperties[$relationKeyMOH]['location_type']);
414 unset($returnProperties[$relationKeyMOH]['im_provider']);
415 unset($returnProperties[$relationKeyHOH]['location_type']);
416 unset($returnProperties[$relationKeyHOH]['im_provider']);
419 $allRelContactArray = $relationQuery = array();
421 foreach ($contactRelationshipTypes as $rel => $dnt) {
422 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
423 $allRelContactArray[$rel] = array();
424 // build Query for each relationship
425 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
426 NULL, FALSE, FALSE, $queryMode
428 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
430 list($id, $direction) = explode('_', $rel, 2);
431 // identify the relationship direction
432 $contactA = 'contact_id_a';
433 $contactB = 'contact_id_b';
434 if ($direction == 'b_a') {
435 $contactA = 'contact_id_b';
436 $contactB = 'contact_id_a';
438 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
441 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
442 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
443 $query = "SELECT contact_id FROM civicrm_activity_contact
444 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
445 record_type_id = {$sourceID}";
446 $dao = CRM_Core_DAO
::executeQuery($query);
447 while ($dao->fetch()) {
448 $relIDs[] = $dao->contact_id
;
452 switch ($exportMode) {
453 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
454 $component = 'civicrm_contribution';
457 case CRM_Export_Form_Select
::EVENT_EXPORT
:
458 $component = 'civicrm_participant';
461 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
462 $component = 'civicrm_membership';
465 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
466 $component = 'civicrm_pledge';
469 case CRM_Export_Form_Select
::GRANT_EXPORT
:
470 $component = 'civicrm_grant';
474 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
475 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
478 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
482 $relationshipJoin = $relationshipClause = '';
483 if (!$selectAll && $componentTable) {
484 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
486 elseif (!empty($relIDs)) {
487 $relID = implode(',', $relIDs);
488 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
491 $relationFrom = " {$relationFrom}
492 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
493 {$relationshipJoin} ";
495 //check for active relationship status only
496 $today = date('Ymd');
497 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
498 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
499 $relationGroupBy = " GROUP BY crel.{$contactA}";
500 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
501 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
503 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
504 while ($allRelContactDAO->fetch()) {
505 //FIX Me: Migrate this to table rather than array
506 // build the array of all related contacts
507 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
509 $allRelContactDAO->free();
513 // make sure the groups stuff is included only if specifically specified
514 // by the fields param (CRM-1969), else we limit the contacts outputted to only
515 // ones that are part of a group
516 if (!empty($returnProperties['groups'])) {
517 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
518 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
519 // total hack for export, CRM-3618
520 $from = str_replace($oldClause,
526 if (!$selectAll && $componentTable) {
527 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
529 elseif ($componentClause) {
531 $where = "WHERE $componentClause";
534 $where .= " AND $componentClause";
538 // CRM-13982 - check if is deleted
539 $excludeTrashed = TRUE;
540 foreach ($params as $value) {
541 if ($value[0] == 'contact_is_deleted') {
542 $excludeTrashed = FALSE;
545 if (empty($where) && $excludeTrashed) {
546 $where = "WHERE contact_a.is_deleted != 1";
548 elseif ($excludeTrashed) {
549 $where .= " AND contact_a.is_deleted != 1";
552 $queryString = "$select $from $where $having";
555 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
556 CRM_Utils_Array
::value('notes', $returnProperties) ||
558 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
560 $groupBy = " GROUP BY contact_a.id";
563 switch ($exportMode) {
564 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
565 $groupBy = 'GROUP BY civicrm_contribution.id';
566 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
567 // especial group by when soft credit columns are included
568 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
572 case CRM_Export_Form_Select
::EVENT_EXPORT
:
573 $groupBy = 'GROUP BY civicrm_participant.id';
576 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
577 $groupBy = " GROUP BY civicrm_membership.id";
581 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
582 $groupBy = " GROUP BY civicrm_activity.id ";
584 $queryString .= $groupBy;
586 list($field, $dir) = explode(' ', $order, 2);
587 $field = trim($field);
588 if (!empty($returnProperties[$field])) {
589 // $queryString .= " ORDER BY $order";
593 $multipleSelectFields = array('preferred_communication_method' => 1);
595 $addPaymentHeader = FALSE;
597 $paymentDetails = array();
598 if ($paymentFields ||
$selectedPaymentFields) {
600 // get payment related in for event and members
601 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
602 //get all payment headers.
603 // If we haven't selected specific payment fields, load in all the
605 if (!$selectedPaymentFields) {
606 $paymentHeaders = self
::componentPaymentFields();
607 if (!empty($paymentDetails)) {
608 $addPaymentHeader = TRUE;
611 // If we have seleted specific payment fields, leave the payment headers
612 // as an empty array; the headers for each selected field will be added
615 $paymentHeaders = array();
617 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
620 // Split campaign into 2 fields for id and title
621 $campaignReturnProperties = array();
622 foreach ($returnProperties as $fld => $true) {
623 $campaignReturnProperties[$fld] = $true;
624 if (substr($fld, -11) == 'campaign_id') {
625 $exportCampaign = TRUE;
626 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
629 $returnProperties = $campaignReturnProperties;
631 if (isset($exportCampaign)) {
632 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
635 $componentDetails = $headerRows = $sqlColumns = array();
638 $rowCount = self
::EXPORT_ROW_COUNT
;
640 // we write to temp table often to avoid using too much memory
645 // for CRM-3157 purposes
646 $i18n = CRM_Core_I18n
::singleton();
649 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
650 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
655 while ($dao->fetch()) {
659 //convert the pseudo constants
660 $query->convertToPseudoNames($dao);
662 //first loop through returnproperties so that we return what is required, and in same order.
663 $relationshipField = 0;
664 foreach ($returnProperties as $field => $value) {
665 //we should set header only once
668 // Split campaign into 2 fields for id and title
669 if (substr($field, -8) == 'campaign') {
670 $headerRows[] = ts('Campaign Title');
672 elseif (substr($field, -11) == 'campaign_id') {
673 $headerRows[] = ts('Campaign ID');
675 elseif (isset($query->_fields
[$field]['title'])) {
676 $headerRows[] = $query->_fields
[$field]['title'];
678 elseif ($field == 'phone_type_id') {
679 $headerRows[] = ts('Phone Type');
681 elseif ($field == 'provider_id') {
682 $headerRows[] = ts('IM Service Provider');
684 elseif (is_array($value) && $field == 'location') {
685 // fix header for location type case
686 foreach ($value as $ltype => $val) {
687 foreach (array_keys($val) as $fld) {
688 $type = explode('-', $fld);
689 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
691 if (!empty($type[1])) {
692 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
693 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
695 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
696 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
699 $headerRows[] = $hdr;
700 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
705 elseif (substr($field, 0, 5) == 'case_') {
706 if ($query->_fields
['case'][$field]['title']) {
707 $headerRows[] = $query->_fields
['case'][$field]['title'];
709 elseif ($query->_fields
['activity'][$field]['title']) {
710 $headerRows[] = $query->_fields
['activity'][$field]['title'];
713 elseif (array_key_exists($field, $contactRelationshipTypes)) {
715 foreach ($value as $relationField => $relationValue) {
716 // below block is same as primary block (duplicate)
717 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
718 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
719 $headerName = $field . '-' . $relationField;
722 if ($relationField == 'current_employer') {
723 $headerName = $field . '-' . 'current_employer';
726 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
730 $headerRows[] = $headerName;
732 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
734 elseif ($relationField == 'phone_type_id') {
735 $headerName = $field . '-' . 'Phone Type';
736 $headerRows[] = $headerName;
737 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
739 elseif ($relationField == 'provider_id') {
740 $headerName = $field . '-' . 'Im Service Provider';
741 $headerRows[] = $headerName;
742 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
744 elseif ($relationField == 'state_province_id') {
745 $headerName = $field . '-' . 'state_province_id';
746 $headerRows[] = $headerName;
747 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
749 elseif (is_array($relationValue) && $relationField == 'location') {
750 // fix header for location type case
751 foreach ($relationValue as $ltype => $val) {
752 foreach (array_keys($val) as $fld) {
753 $type = explode('-', $fld);
755 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
757 if (!empty($type[1])) {
758 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
759 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
761 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
762 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
765 $headerName = $field . '-' . $hdr;
766 $headerRows[] = $headerName;
767 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
773 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
774 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
777 $headerRows[] = $field;
781 self
::sqlColumnDefn($query, $sqlColumns, $field);
785 // add im_provider to $dao object
786 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
787 $dao->im_provider
= $dao->provider_id
;
790 //build row values (data)
792 if (property_exists($dao, $field)) {
793 $fieldValue = $dao->$field;
794 // to get phone type from phone type id
795 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
796 $fieldValue = $phoneTypes[$fieldValue];
798 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
799 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
801 elseif ($field == 'participant_role_id') {
802 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
803 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
804 $viewRoles = array();
805 foreach (explode($sep, $dao->$field) as $k => $v) {
806 $viewRoles[] = $participantRoles[$v];
808 $fieldValue = implode(',', $viewRoles);
810 elseif ($field == 'master_id') {
811 $masterAddressId = NULL;
812 if (isset($dao->master_id
)) {
813 $masterAddressId = $dao->master_id
;
815 // get display name of contact that address is shared.
816 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $dao->contact_id
);
820 if ($field == 'id') {
821 $row[$field] = $dao->contact_id
;
822 // special case for calculated field
824 elseif ($field == 'source_contact_id') {
825 $row[$field] = $dao->contact_id
;
827 elseif ($field == 'pledge_balance_amount') {
828 $row[$field] = $dao->pledge_amount
- $dao->pledge_total_paid
;
829 // special case for calculated field
831 elseif ($field == 'pledge_next_pay_amount') {
832 $row[$field] = $dao->pledge_next_pay_amount +
$dao->pledge_outstanding_amount
;
834 elseif (in_array(substr($field, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
835 $row[$field] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', $field, $dao->$field);
837 elseif (is_array($value) && $field == 'location') {
838 // fix header for location type case
839 foreach ($value as $ltype => $val) {
840 foreach (array_keys($val) as $fld) {
841 $type = explode('-', $fld);
842 $fldValue = "{$ltype}-" . $type[0];
843 // CRM-14076 - fix label to work as the query object expects
844 // FIXME: We should not be using labels as keys!
845 $daoField = CRM_Utils_String
::munge($ltype) . '-' . $type[0];
847 if (!empty($type[1])) {
848 $fldValue .= "-" . $type[1];
849 $daoField .= "-" . $type[1];
852 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
856 $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'country'));
859 case 'state_province':
860 $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'province'));
864 $imFieldvalue = $daoField . "-provider_id";
865 $row[$fldValue] = CRM_Utils_Array
::value($dao->$imFieldvalue, $imProviders);
869 $row[$fldValue] = $dao->$daoField;
875 elseif (array_key_exists($field, $contactRelationshipTypes)) {
876 $relDAO = CRM_Utils_Array
::value($dao->contact_id
, $allRelContactArray[$field]);
877 foreach ($value as $relationField => $relationValue) {
878 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
879 $fieldValue = $relDAO->$relationField;
880 if ($relationField == 'phone_type_id') {
881 $fieldValue = $phoneTypes[$relationValue];
883 elseif ($relationField == 'provider_id') {
884 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
888 elseif (is_object($relDAO) && in_array($relationField, array(
889 'email_greeting', 'postal_greeting', 'addressee'))) {
890 //special case for greeting replacement
891 $fldValue = "{$relationField}_display";
892 $fieldValue = $relDAO->$fldValue;
894 elseif ( is_object($relDAO) && $relationField == 'state_province' ) {
895 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
897 elseif ( is_object($relDAO) && $relationField == 'country' ) {
898 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
903 $field = $field . '_';
905 if (is_object($relDAO) && $relationField == 'id') {
906 $row[$field . $relationField] = $relDAO->contact_id
;
908 elseif ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
909 foreach ($relationValue as $ltype => $val) {
910 foreach (array_keys($val) as $fld) {
911 $type = explode('-', $fld);
912 $fldValue = "{$ltype}-" . $type[0];
913 if (!empty($type[1])) {
914 $fldValue .= "-" . $type[1];
916 // CRM-3157: localise country, region (both have ‘country’ context)
917 // and state_province (‘province’ context)
919 case (!is_object($relDAO)):
920 $row[$field . '_' . $fldValue] = '';
923 case in_array('country', $type):
924 case in_array('world_region', $type):
925 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
926 array('context' => 'country')
930 case in_array('state_province', $type):
931 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
932 array('context' => 'province')
937 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
943 elseif (isset($fieldValue) && $fieldValue != '') {
944 //check for custom data
945 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
946 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
947 $relationQuery[$field]->_options
951 //normal relationship fields
952 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
953 switch ($relationField) {
956 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
959 case 'state_province':
960 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
964 $row[$field . $relationField] = $fieldValue;
970 // if relation field is empty or null
971 $row[$field . $relationField] = '';
975 elseif (isset($fieldValue) &&
978 //check for custom data
979 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
980 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
982 elseif (array_key_exists($field, $multipleSelectFields)) {
984 $paramsNew = array($field => $fieldValue);
985 if ($field == 'test_tutoring') {
986 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
989 elseif (substr($field, 0, 4) == 'cmr_') {
990 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
993 $name = array($field => array('newName' => $field, 'groupName' => $field));
995 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
996 $row[$field] = $paramsNew[$field];
998 elseif (in_array($field, array(
999 'email_greeting', 'postal_greeting', 'addressee'))) {
1000 //special case for greeting replacement
1001 $fldValue = "{$field}_display";
1002 $row[$field] = $dao->$fldValue;
1005 //normal fields with a touch of CRM-3157
1008 case 'world_region':
1009 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1012 case 'state_province':
1013 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1017 case 'preferred_communication_method':
1018 case 'preferred_mail_format':
1019 case 'communication_style':
1020 $row[$field] = $i18n->crm_translate($fieldValue);
1024 $row[$field] = $fieldValue;
1029 elseif (substr($field, -8) == 'campaign') {
1030 $campIdFld = "{$field}_id";
1031 $row[$field] = CRM_Utils_Array
::value($dao->$campIdFld, $allCampaigns, '');
1033 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1034 $paymentData = CRM_Utils_Array
::value($dao->$paymentTableId, $paymentDetails);
1035 $payFieldMapper = array(
1036 'componentPaymentField_total_amount' => 'total_amount',
1037 'componentPaymentField_contribution_status' => 'contribution_status',
1038 'componentPaymentField_payment_instrument' => 'pay_instru',
1039 'componentPaymentField_transaction_id' => 'trxn_id',
1040 'componentPaymentField_received_date' => 'receive_date',
1042 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1045 // if field is empty or null
1050 // add payment headers if required
1051 if ($addPaymentHeader && $paymentFields) {
1052 $headerRows = array_merge($headerRows, $paymentHeaders);
1053 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1054 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1059 $exportTempTable = self
::createTempTable($sqlColumns);
1062 //build header only once
1065 // If specific payment fields have been selected for export, payment
1066 // data will already be in $row. Otherwise, add payment related
1067 // information, if appropriate.
1068 if ($addPaymentHeader) {
1069 if (!$selectedPaymentFields) {
1070 if ($paymentFields) {
1071 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1072 if (!is_array($paymentData) ||
empty($paymentData)) {
1073 $paymentData = $nullContributionDetails;
1075 $row = array_merge($row, $paymentData);
1077 elseif (!empty($paymentDetails)) {
1078 $row = array_merge($row, $nullContributionDetails);
1082 //remove organization name for individuals if it is set for current employer
1083 if (!empty($row['contact_type']) &&
1084 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1086 $row['organization_name'] = '';
1089 // add component info
1090 // write the row to a file
1091 $componentDetails[] = $row;
1093 // output every $tempRowCount rows
1094 if ($count %
$tempRowCount == 0) {
1095 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1096 $componentDetails = array();
1100 $offset +
= $rowCount;
1103 if ($exportTempTable) {
1104 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1106 // do merge same address and merge same household processing
1107 if ($mergeSameAddress) {
1108 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1111 // merge the records if they have corresponding households
1112 if ($mergeSameHousehold) {
1113 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1114 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1117 // fix the headers for rows with relationship type
1118 if (!empty($relName)) {
1119 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1122 // if postalMailing option is checked, exclude contacts who are deceased, have
1123 // "Do not mail" privacy setting, or have no street address
1124 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1125 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1127 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1131 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1133 // now write the CSV file
1134 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1136 // delete the export temp table and component table
1137 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1138 CRM_Core_DAO
::executeQuery($sql);
1140 CRM_Utils_System
::civiExit();
1143 CRM_Core_Error
::fatal(ts('No records to export'));
1148 * name of the export file based on mode
1150 * @param string $output type of output
1151 * @param int $mode export mode
1153 * @return string name of the file
1155 static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1157 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1158 return ts('CiviCRM Contact Search');
1160 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1161 return ts('CiviCRM Contribution Search');
1163 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1164 return ts('CiviCRM Member Search');
1166 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1167 return ts('CiviCRM Participant Search');
1169 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1170 return ts('CiviCRM Pledge Search');
1172 case CRM_Export_Form_Select
::CASE_EXPORT
:
1173 return ts('CiviCRM Case Search');
1175 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1176 return ts('CiviCRM Grant Search');
1178 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1179 return ts('CiviCRM Activity Search');
1184 * Function to handle import error file creation.
1187 static function invoke() {
1188 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1189 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1190 if (empty($parserName) ||
empty($type)) {
1194 // clean and ensure parserName is a valid string
1195 $parserName = CRM_Utils_String
::munge($parserName);
1196 $parserClass = explode('_', $parserName);
1198 // make sure parserClass is in the CRM namespace and
1199 // at least 3 levels deep
1200 if ($parserClass[0] == 'CRM' &&
1201 count($parserClass) >= 3
1203 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php");
1204 // ensure the functions exists
1205 if (method_exists($parserName, 'errorFileName') &&
1206 method_exists($parserName, 'saveFileName')
1208 $errorFileName = $parserName::errorFileName($type);
1209 $saveFileName = $parserName::saveFileName($type);
1210 if (!empty($errorFileName) && !empty($saveFileName)) {
1211 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1212 header('Content-Description: File Transfer');
1213 header('Content-Type: text/csv');
1214 header('Content-Length: ' . filesize($errorFileName));
1215 header('Content-Disposition: attachment; filename=' . $saveFileName);
1217 readfile($errorFileName);
1221 CRM_Utils_System
::civiExit();
1224 static function exportCustom($customSearchClass, $formValues, $order) {
1225 $ext = CRM_Extension_System
::singleton()->getMapper();
1226 if (!$ext->isExtensionClass($customSearchClass)) {
1227 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php');
1230 require_once ($ext->classToPath($customSearchClass));
1232 $search = new $customSearchClass($formValues);
1234 $includeContactIDs = FALSE;
1235 if ($formValues['radio_ts'] == 'ts_sel') {
1236 $includeContactIDs = TRUE;
1239 $sql = $search->all(0, 0, $order, $includeContactIDs);
1241 $columns = $search->columns();
1243 $header = array_keys($columns);
1244 $fields = array_values($columns);
1247 $dao = CRM_Core_DAO
::executeQuery($sql);
1249 if (method_exists($search, 'alterRow')) {
1252 while ($dao->fetch()) {
1255 foreach ($fields as $field) {
1256 $row[$field] = $dao->$field;
1259 $search->alterRow($row);
1264 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1265 CRM_Utils_System
::civiExit();
1268 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1269 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1273 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1274 if ($fieldName == 'id') {
1275 $fieldName = 'civicrm_primary_id';
1278 // early exit for master_id, CRM-12100
1279 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1280 if ($fieldName == 'master_id') {
1281 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1285 // set the sql columns
1286 if (isset($query->_fields
[$field]['type'])) {
1287 switch ($query->_fields
[$field]['type']) {
1288 case CRM_Utils_Type
::T_INT
:
1289 case CRM_Utils_Type
::T_BOOLEAN
:
1290 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1293 case CRM_Utils_Type
::T_STRING
:
1294 if (isset($query->_fields
[$field]['maxlength'])) {
1295 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1298 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1302 case CRM_Utils_Type
::T_TEXT
:
1303 case CRM_Utils_Type
::T_LONGTEXT
:
1304 case CRM_Utils_Type
::T_BLOB
:
1305 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1306 $sqlColumns[$fieldName] = "$fieldName longtext";
1309 case CRM_Utils_Type
::T_FLOAT
:
1310 case CRM_Utils_Type
::T_ENUM
:
1311 case CRM_Utils_Type
::T_DATE
:
1312 case CRM_Utils_Type
::T_TIME
:
1313 case CRM_Utils_Type
::T_TIMESTAMP
:
1314 case CRM_Utils_Type
::T_MONEY
:
1315 case CRM_Utils_Type
::T_EMAIL
:
1316 case CRM_Utils_Type
::T_URL
:
1317 case CRM_Utils_Type
::T_CCNUM
:
1319 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1324 if (substr($fieldName, -3, 3) == '_id') {
1325 // for trxn_id and its variants use a longer buffer
1326 // to accomodate different systems - CRM-13739
1327 static $notRealIDFields = NULL;
1328 if ($notRealIDFields == NULL) {
1329 $notRealIDFields = array( 'trxn_id', 'componentpaymentfield_transaction_id' );
1332 if (in_array($fieldName, $notRealIDFields)) {
1333 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1336 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1340 $changeFields = array(
1346 if (in_array($fieldName, $changeFields)) {
1347 $sqlColumns[$fieldName] = "$fieldName text";
1350 // set the sql columns for custom data
1351 if (isset($query->_fields
[$field]['data_type'])) {
1353 switch ($query->_fields
[$field]['data_type']) {
1355 case 'StateProvince':
1358 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1362 $sqlColumns[$fieldName] = "$fieldName text";
1366 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1371 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1378 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1379 if (empty($details)) {
1388 $id = CRM_Core_DAO
::singleValueQuery($sql);
1393 $sqlClause = array();
1395 foreach ($details as $dontCare => $row) {
1397 $valueString = array($id);
1398 foreach ($row as $dontCare => $value) {
1399 if (empty($value)) {
1400 $valueString[] = "''";
1403 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1406 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1409 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1411 $sqlValueString = implode(",\n", $sqlClause);
1414 INSERT INTO $tableName $sqlColumnString
1415 VALUES $sqlValueString
1418 CRM_Core_DAO
::executeQuery($sql);
1421 static function createTempTable(&$sqlColumns) {
1422 //creating a temporary table for the search result that need be exported
1423 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1425 // also create the sql table
1426 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1427 CRM_Core_DAO
::executeQuery($sql);
1430 CREATE TABLE {$exportTempTable} (
1431 id int unsigned NOT NULL AUTO_INCREMENT,
1433 $sql .= implode(",\n", array_values($sqlColumns));
1438 // add indexes for street_address and household_name if present
1439 $addIndices = array(
1442 'civicrm_primary_id',
1445 foreach ($addIndices as $index) {
1446 if (isset($sqlColumns[$index])) {
1448 INDEX index_{$index}( $index )
1454 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1457 CRM_Core_DAO
::executeQuery($sql);
1458 return $exportTempTable;
1461 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1462 // check if any records are present based on if they have used shared address feature,
1463 // and not based on if city / state .. matches.
1465 SELECT r1.id as copy_id,
1466 r1.civicrm_primary_id as copy_contact_id,
1467 r1.addressee as copy_addressee,
1468 r1.addressee_id as copy_addressee_id,
1469 r1.postal_greeting as copy_postal_greeting,
1470 r1.postal_greeting_id as copy_postal_greeting_id,
1472 r2.civicrm_primary_id as master_contact_id,
1473 r2.postal_greeting as master_postal_greeting,
1474 r2.postal_greeting_id as master_postal_greeting_id,
1475 r2.addressee as master_addressee,
1476 r2.addressee_id as master_addressee_id
1478 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1479 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1481 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1483 // find all the records that have the same street address BUT not in a household
1484 // require match on city and state as well
1486 SELECT r1.id as master_id,
1487 r1.civicrm_primary_id as master_contact_id,
1488 r1.postal_greeting as master_postal_greeting,
1489 r1.postal_greeting_id as master_postal_greeting_id,
1490 r1.addressee as master_addressee,
1491 r1.addressee_id as master_addressee_id,
1493 r2.civicrm_primary_id as copy_contact_id,
1494 r2.postal_greeting as copy_postal_greeting,
1495 r2.postal_greeting_id as copy_postal_greeting_id,
1496 r2.addressee as copy_addressee,
1497 r2.addressee_id as copy_addressee_id
1499 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1500 r1.city = r2.city AND
1501 r1.state_province_id = r2.state_province_id )
1502 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1503 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1504 AND ( r1.street_address != '' )
1508 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1510 // unset ids from $merge already present in $linkedMerge
1511 foreach ($linkedMerge as $masterID => $values) {
1512 $keys = array($masterID);
1513 $keys = array_merge($keys, array_keys($values['copy']));
1514 foreach ($merge as $mid => $vals) {
1515 if (in_array($mid, $keys)) {
1516 unset($merge[$mid]);
1519 foreach ($values['copy'] as $copyId) {
1520 if (in_array($copyId, $keys)) {
1521 unset($merge[$mid]['copy'][$copyId]);
1527 $merge = $merge +
$linkedMerge;
1529 foreach ($merge as $masterID => $values) {
1532 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1535 $params = array(1 => array($values['addressee'], 'String'),
1536 2 => array($values['postalGreeting'], 'String'),
1537 3 => array($values['emailGreeting'], 'String'),
1538 4 => array($masterID, 'Integer'),
1540 CRM_Core_DAO
::executeQuery($sql, $params);
1542 // delete all copies
1543 $deleteIDs = array_keys($values['copy']);
1544 $deleteIDString = implode(',', $deleteIDs);
1546 DELETE FROM $tableName
1547 WHERE id IN ( $deleteIDString )
1549 CRM_Core_DAO
::executeQuery($sql);
1552 // unset temporary columns that were added for postal mailing format
1553 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1554 $unsetKeys = array_keys($sqlColumns);
1555 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1556 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1557 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1563 static function _replaceMergeTokens($contactId, $exportParams) {
1564 $greetings = array();
1567 $greetingFields = array(
1571 foreach ($greetingFields as $greeting) {
1572 if (!empty($exportParams[$greeting])) {
1573 $greetingLabel = $exportParams[$greeting];
1574 if (empty($contact)) {
1579 $contact = civicrm_api('contact', 'get', $values);
1581 if (!empty($contact['is_error'])) {
1584 $contact = $contact['values'][$contact['id']];
1587 $tokens = array('contact' => $greetingLabel);
1588 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1595 * The function unsets static part of the string, if token is the dynamic part.
1596 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1597 * i.e 'Hello Alan' => converted to => 'Alan'
1600 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1601 $addressMergeGreetings, $greetingType = 'postal_greeting'
1603 if (!empty($addressMergeGreetings[$greetingType])) {
1604 $greetingLabel = $addressMergeGreetings[$greetingType];
1606 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1608 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1609 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1610 foreach ($stringsToBeReplaced as $key => $string) {
1611 // to keep one space
1612 $stringsToBeReplaced[$key] = ltrim($string);
1614 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1616 return $parsedString;
1619 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1620 static $contactGreetingTokens = array();
1622 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1623 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1625 $merge = $parents = array();
1626 $dao = CRM_Core_DAO
::executeQuery($sql);
1628 while ($dao->fetch()) {
1629 $masterID = $dao->master_id
;
1630 $copyID = $dao->copy_id
;
1631 $masterPostalGreeting = $dao->master_postal_greeting
;
1632 $masterAddressee = $dao->master_addressee
;
1633 $copyAddressee = $dao->copy_addressee
;
1635 if (!$sharedAddress) {
1636 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1637 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1639 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1640 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1642 $masterAddressee = CRM_Utils_Array
::value('addressee',
1643 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1646 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1647 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1649 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1650 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1652 $copyAddressee = CRM_Utils_Array
::value('addressee',
1653 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1657 if (!isset($merge[$masterID])) {
1658 // check if this is an intermediate child
1659 // this happens if there are 3 or more matches a,b, c
1660 // the above query will return a, b / a, c / b, c
1661 // we might be doing a bit more work, but for now its ok, unless someone
1662 // knows how to fix the query above
1663 if (isset($parents[$masterID])) {
1664 $masterID = $parents[$masterID];
1667 $merge[$masterID] = array(
1668 'addressee' => $masterAddressee,
1670 'postalGreeting' => $masterPostalGreeting,
1672 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1675 $parents[$copyID] = $masterID;
1677 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1679 if (!empty($exportParams['postal_greeting_other']) &&
1680 count($merge[$masterID]['copy']) >= 1
1682 // use static greetings specified if no of contacts > 2
1683 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1685 elseif ($copyPostalGreeting) {
1686 self
::_trimNonTokens($copyPostalGreeting,
1687 $postalOptions[$dao->copy_postal_greeting_id
],
1690 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1691 // if there happens to be a duplicate, remove it
1692 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1695 if (!empty($exportParams['addressee_other']) &&
1696 count($merge[$masterID]['copy']) >= 1
1698 // use static greetings specified if no of contacts > 2
1699 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1701 elseif ($copyAddressee) {
1702 self
::_trimNonTokens($copyAddressee,
1703 $addresseeOptions[$dao->copy_addressee_id
],
1704 $exportParams, 'addressee'
1706 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1709 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1716 * Function to merge household record into the individual record
1719 * @param string $exportTempTable temporary temp table that stores the records
1720 * @param array $headerRows array of headers for the export file
1721 * @param array $sqlColumns array of names of the table columns of the temp table
1722 * @param string $prefix name of the relationship type that is prefixed to the table columns
1724 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1725 $prefixColumn = $prefix . '_';
1726 $allKeys = array_keys($sqlColumns);
1727 $replaced = array();
1728 $headerRows = array_values($headerRows);
1730 // name map of the non standard fields in header rows & sql columns
1731 $mappingFields = array(
1732 'civicrm_primary_id' => 'id',
1733 'contact_source' => 'source',
1734 'current_employer_id' => 'employer_id',
1735 'contact_is_deleted' => 'is_deleted',
1736 'name' => 'address_name',
1737 'provider_id' => 'im_service_provider',
1738 'phone_type_id' => 'phone_type'
1741 //figure out which columns are to be replaced by which ones
1742 foreach ($sqlColumns as $columnNames => $dontCare) {
1743 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1744 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1747 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1749 if (!empty($sqlColumns[$householdColName])) {
1750 $replaced[$columnNames] = $householdColName;
1754 $query = "UPDATE $exportTempTable SET ";
1757 foreach ($replaced as $from => $to) {
1758 $clause[] = "$from = $to ";
1759 unset($sqlColumns[$to]);
1760 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1761 unset($headerRows[$key]);
1764 $query .= implode(",\n", $clause);
1765 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1767 CRM_Core_DAO
::executeQuery($query);
1769 //drop the table columns that store redundant household info
1770 $dropQuery = "ALTER TABLE $exportTempTable ";
1771 foreach ($replaced as $householdColumns) {
1772 $dropClause[] = " DROP $householdColumns ";
1774 $dropQuery .= implode(",\n", $dropClause);
1776 CRM_Core_DAO
::executeQuery($dropQuery);
1778 // also drop the temp table if exists
1779 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1780 CRM_Core_DAO
::executeQuery($sql);
1782 // clean up duplicate records
1784 CREATE TABLE {$exportTempTable}_temp SELECT *
1785 FROM {$exportTempTable}
1786 GROUP BY civicrm_primary_id ";
1788 CRM_Core_DAO
::executeQuery($query);
1790 $query = "DROP TABLE $exportTempTable";
1791 CRM_Core_DAO
::executeQuery($query);
1793 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1794 CRM_Core_DAO
::executeQuery($query);
1797 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1798 $writeHeader = TRUE;
1800 $limit = self
::EXPORT_ROW_COUNT
;
1802 $query = "SELECT * FROM $exportTempTable";
1805 $limitQuery = $query . "
1806 LIMIT $offset, $limit
1808 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1814 $componentDetails = array();
1815 while ($dao->fetch()) {
1818 foreach ($sqlColumns as $column => $dontCare) {
1819 $row[$column] = $dao->$column;
1821 $componentDetails[] = $row;
1823 if ( $exportMode == 'financial' ) {
1824 $getExportFileName = 'CiviCRM Contribution Search';
1827 $getExportFileName =self
::getExportFileName( 'csv', $exportMode );
1829 $csvRows = CRM_Core_Report_Excel
::writeCSVFile( $getExportFileName,
1836 if ($saveFile && !empty($csvRows)) {
1837 $batchItems .= $csvRows;
1840 $writeHeader = false;
1846 * Function to manipulate header rows for relationship fields
1849 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1850 foreach ($headerRows as & $header) {
1851 $split = explode('-', $header);
1852 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1853 $split[0] = $relationTypeName;
1854 $header = implode('-', $split);
1860 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1861 * or have no street address
1864 static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1865 $whereClause = array();
1867 if (array_key_exists('is_deceased', $sqlColumns)) {
1868 $whereClause[] = 'is_deceased = 1';
1871 if (array_key_exists('do_not_mail', $sqlColumns)) {
1872 $whereClause[] = 'do_not_mail = 1';
1875 if (array_key_exists('street_address', $sqlColumns)) {
1876 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1878 // check for supplemental_address_1
1879 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1880 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1881 'address_options', TRUE, NULL, TRUE
1883 if (!empty($addressOptions['supplemental_address_1'])) {
1884 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1885 // enclose it again, since we are doing an AND in between a set of ORs
1886 $addressWhereClause = "( $addressWhereClause )";
1890 $whereClause[] = $addressWhereClause;
1893 if (!empty($whereClause)) {
1894 $whereClause = implode(' OR ', $whereClause);
1897 FROM $exportTempTable
1898 WHERE {$whereClause}";
1899 CRM_Core_DAO
::singleValueQuery($query);
1902 // unset temporary columns that were added for postal mailing format
1903 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1904 $unsetKeys = array_keys($sqlColumns);
1905 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1906 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1907 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1914 * Build componentPayment fields.
1916 static function componentPaymentFields() {
1917 static $componentPaymentFields;
1918 if (!isset( $componentPaymentFields)) {
1919 $componentPaymentFields = array(
1920 'componentPaymentField_total_amount' => ts('Total Amount'),
1921 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1922 'componentPaymentField_received_date' => ts('Received Date'),
1923 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1924 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1927 return $componentPaymentFields;