3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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
61 * @param array $exportParams
62 * @param string $queryOperator
67 static function exportComponents($selectAll,
72 $moreReturnProperties = NULL,
73 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
74 $componentClause = NULL,
75 $componentTable = NULL,
76 $mergeSameAddress = FALSE,
77 $mergeSameHousehold = FALSE,
78 $exportParams = array(),
79 $queryOperator = 'AND'
81 $headerRows = $returnProperties = array();
82 $primary = $paymentFields = $selectedPaymentFields = FALSE;
83 $origFields = $fields;
84 $queryMode = $relationField = NULL;
86 $allCampaigns = array();
88 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
89 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
90 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
99 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
101 switch ($exportMode) {
102 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
103 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
106 case CRM_Export_Form_Select
::EVENT_EXPORT
:
107 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
110 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
111 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
114 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
115 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
118 case CRM_Export_Form_Select
::CASE_EXPORT
:
119 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
122 case CRM_Export_Form_Select
::GRANT_EXPORT
:
123 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
126 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
127 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
131 //construct return properties
132 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
133 $locationTypeFields = array(
135 'supplemental_address_1',
136 'supplemental_address_2',
139 'postal_code_suffix',
149 foreach ($fields as $key => $value) {
150 $phoneTypeId = $imProviderId = NULL;
151 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
155 // get phoneType id and IM service provider id seperately
156 if ($fieldName == 'phone') {
157 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
159 elseif ($fieldName == 'im') {
160 $imProviderId = CRM_Utils_Array
::value(3, $value);
163 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
164 if (!empty($value[2])) {
165 $relationField = CRM_Utils_Array
::value(2, $value);
166 if (trim(CRM_Utils_Array
::value(3, $value))) {
167 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
170 $relLocTypeId = 'Primary';
173 if ($relationField == 'phone') {
174 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
176 elseif ($relationField == 'im') {
177 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
180 elseif (!empty($value[4])) {
181 $relationField = CRM_Utils_Array
::value(4, $value);
182 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
183 if ($relationField == 'phone') {
184 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
186 elseif ($relationField == 'im') {
187 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
192 $contactType = CRM_Utils_Array
::value(0, $value);
193 $locTypeId = CRM_Utils_Array
::value(2, $value);
195 if ($relationField) {
196 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
197 if ($relPhoneTypeId) {
198 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
200 elseif ($relIMProviderId) {
201 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
204 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
206 $relPhoneTypeId = $relIMProviderId = NULL;
209 $returnProperties[$relationshipTypes][$relationField] = 1;
212 elseif (is_numeric($locTypeId)) {
214 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
216 elseif ($imProviderId) {
217 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
220 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
224 //hack to fix component fields
225 if ($fieldName == 'event_id') {
226 $returnProperties['event_title'] = 1;
229 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
230 array_key_exists( $fieldName, self
::componentPaymentFields())
232 $selectedPaymentFields = true;
233 $paymentTableId = 'participant_id';
234 $returnProperties[$fieldName] = 1;
237 $returnProperties[$fieldName] = 1;
242 // hack to add default returnproperty based on export mode
243 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
244 $returnProperties['contribution_id'] = 1;
246 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
247 $returnProperties['participant_id'] = 1;
248 if (!empty($returnProperties['participant_role'])) {
249 unset($returnProperties['participant_role']);
250 $returnProperties['participant_role_id'] = 1;
253 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
254 $returnProperties['membership_id'] = 1;
256 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
257 $returnProperties['pledge_id'] = 1;
259 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
260 $returnProperties['case_id'] = 1;
262 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
263 $returnProperties['grant_id'] = 1;
265 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
266 $returnProperties['activity_id'] = 1;
271 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
272 foreach ($fields as $key => $var) {
273 if ($key && (substr($key, 0, 6) != 'custom')) {
275 $returnProperties[$key] = 1;
280 $returnProperties['location_type'] = 1;
281 $returnProperties['im_provider'] = 1;
282 $returnProperties['phone_type_id'] = 1;
283 $returnProperties['provider_id'] = 1;
284 $returnProperties['current_employer'] = 1;
287 $extraReturnProperties = array();
288 $paymentFields = FALSE;
290 switch ($queryMode) {
291 case CRM_Contact_BAO_Query
::MODE_EVENT
:
292 $paymentFields = TRUE;
293 $paymentTableId = 'participant_id';
296 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
297 $paymentFields = TRUE;
298 $paymentTableId = 'membership_id';
301 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
302 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
303 $paymentFields = TRUE;
304 $paymentTableId = 'pledge_payment_id';
307 case CRM_Contact_BAO_Query
::MODE_CASE
:
308 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
312 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
313 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
314 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
315 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
316 $componentReturnProperties =
318 $componentReturnProperties,
319 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
321 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
323 if (!empty($extraReturnProperties)) {
324 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
327 // unset non exportable fields for components
328 $nonExpoFields = array(
329 'groups', 'tags', 'notes', 'contribution_status_id',
330 'pledge_status_id', 'pledge_payment_status_id',
332 foreach ($nonExpoFields as $value) {
333 unset($returnProperties[$value]);
338 if ($mergeSameAddress) {
339 //make sure the addressee fields are selected
340 //while using merge same address feature
341 $returnProperties['addressee'] = 1;
342 $returnProperties['postal_greeting'] = 1;
343 $returnProperties['email_greeting'] = 1;
344 $returnProperties['street_name'] = 1;
345 $returnProperties['household_name'] = 1;
346 $returnProperties['street_address'] = 1;
347 $returnProperties['city'] = 1;
348 $returnProperties['state_province'] = 1;
350 // some columns are required for assistance incase they are not already present
351 $exportParams['merge_same_address']['temp_columns'] = array();
352 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
353 foreach ($tempColumns as $column) {
354 if (!array_key_exists($column, $returnProperties)) {
355 $returnProperties[$column] = 1;
356 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
357 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
362 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
363 // If an Additional Group is selected, then all contacts in that group are
364 // added to the export set (filtering out duplicates).
366 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";
367 CRM_Core_DAO
::executeQuery($query);
370 if ($moreReturnProperties) {
372 if (!empty($moreReturnProperties['group'])) {
373 unset($moreReturnProperties['group']);
374 $moreReturnProperties['groups'] = 1;
376 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
379 $exportParams['postal_mailing_export']['temp_columns'] = array();
380 if ($exportParams['exportOption'] == 2 &&
381 isset($exportParams['postal_mailing_export']) &&
382 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
384 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
385 foreach ($postalColumns as $column) {
386 if (!array_key_exists($column, $returnProperties)) {
387 $returnProperties[$column] = 1;
388 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
393 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
394 FALSE, FALSE, $queryMode,
395 FALSE, TRUE, TRUE, NULL, $queryOperator
398 list($select, $from, $where, $having) = $query->query();
400 if ($mergeSameHousehold == 1) {
401 if (!$returnProperties['id']) {
402 $returnProperties['id'] = 1;
405 //also merge Head of Household
406 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
407 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
409 foreach ($returnProperties as $key => $value) {
410 if (!array_key_exists($key, $contactRelationshipTypes)) {
411 $returnProperties[$relationKeyMOH][$key] = $value;
412 $returnProperties[$relationKeyHOH][$key] = $value;
416 unset($returnProperties[$relationKeyMOH]['location_type']);
417 unset($returnProperties[$relationKeyMOH]['im_provider']);
418 unset($returnProperties[$relationKeyHOH]['location_type']);
419 unset($returnProperties[$relationKeyHOH]['im_provider']);
422 $allRelContactArray = $relationQuery = array();
424 foreach ($contactRelationshipTypes as $rel => $dnt) {
425 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
426 $allRelContactArray[$rel] = array();
427 // build Query for each relationship
428 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
429 NULL, FALSE, FALSE, $queryMode
431 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
433 list($id, $direction) = explode('_', $rel, 2);
434 // identify the relationship direction
435 $contactA = 'contact_id_a';
436 $contactB = 'contact_id_b';
437 if ($direction == 'b_a') {
438 $contactA = 'contact_id_b';
439 $contactB = 'contact_id_a';
441 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
444 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
445 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
446 $query = "SELECT contact_id FROM civicrm_activity_contact
447 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
448 record_type_id = {$sourceID}";
449 $dao = CRM_Core_DAO
::executeQuery($query);
450 while ($dao->fetch()) {
451 $relIDs[] = $dao->contact_id
;
455 switch ($exportMode) {
456 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
457 $component = 'civicrm_contribution';
460 case CRM_Export_Form_Select
::EVENT_EXPORT
:
461 $component = 'civicrm_participant';
464 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
465 $component = 'civicrm_membership';
468 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
469 $component = 'civicrm_pledge';
472 case CRM_Export_Form_Select
::GRANT_EXPORT
:
473 $component = 'civicrm_grant';
477 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
478 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
481 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
485 $relationshipJoin = $relationshipClause = '';
486 if (!$selectAll && $componentTable) {
487 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
489 elseif (!empty($relIDs)) {
490 $relID = implode(',', $relIDs);
491 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
494 $relationFrom = " {$relationFrom}
495 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
496 {$relationshipJoin} ";
498 //check for active relationship status only
499 $today = date('Ymd');
500 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
501 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
502 $relationGroupBy = " GROUP BY crel.{$contactA}";
503 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
504 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
506 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
507 while ($allRelContactDAO->fetch()) {
508 //FIX Me: Migrate this to table rather than array
509 // build the array of all related contacts
510 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
512 $allRelContactDAO->free();
516 // make sure the groups stuff is included only if specifically specified
517 // by the fields param (CRM-1969), else we limit the contacts outputted to only
518 // ones that are part of a group
519 if (!empty($returnProperties['groups'])) {
520 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
521 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
522 // total hack for export, CRM-3618
523 $from = str_replace($oldClause,
529 if (!$selectAll && $componentTable) {
530 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
532 elseif ($componentClause) {
534 $where = "WHERE $componentClause";
537 $where .= " AND $componentClause";
541 // CRM-13982 - check if is deleted
542 $excludeTrashed = TRUE;
543 foreach ($params as $value) {
544 if ($value[0] == 'contact_is_deleted') {
545 $excludeTrashed = FALSE;
548 if (empty($where) && $excludeTrashed) {
549 $where = "WHERE contact_a.is_deleted != 1";
551 elseif ($excludeTrashed) {
552 $where .= " AND contact_a.is_deleted != 1";
555 $queryString = "$select $from $where $having";
558 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
559 CRM_Utils_Array
::value('notes', $returnProperties) ||
561 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
563 $groupBy = " GROUP BY contact_a.id";
566 switch ($exportMode) {
567 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
568 $groupBy = 'GROUP BY civicrm_contribution.id';
569 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
570 // especial group by when soft credit columns are included
571 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
575 case CRM_Export_Form_Select
::EVENT_EXPORT
:
576 $groupBy = 'GROUP BY civicrm_participant.id';
579 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
580 $groupBy = " GROUP BY civicrm_membership.id";
584 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
585 $groupBy = " GROUP BY civicrm_activity.id ";
587 $queryString .= $groupBy;
589 list($field, $dir) = explode(' ', $order, 2);
590 $field = trim($field);
591 if (!empty($returnProperties[$field])) {
592 // $queryString .= " ORDER BY $order";
596 $multipleSelectFields = array('preferred_communication_method' => 1);
598 $addPaymentHeader = FALSE;
600 $paymentDetails = array();
601 if ($paymentFields ||
$selectedPaymentFields) {
603 // get payment related in for event and members
604 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
605 //get all payment headers.
606 // If we haven't selected specific payment fields, load in all the
608 if (!$selectedPaymentFields) {
609 $paymentHeaders = self
::componentPaymentFields();
610 if (!empty($paymentDetails)) {
611 $addPaymentHeader = TRUE;
614 // If we have seleted specific payment fields, leave the payment headers
615 // as an empty array; the headers for each selected field will be added
618 $paymentHeaders = array();
620 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
623 // Split campaign into 2 fields for id and title
624 $campaignReturnProperties = array();
625 foreach ($returnProperties as $fld => $true) {
626 $campaignReturnProperties[$fld] = $true;
627 if (substr($fld, -11) == 'campaign_id') {
628 $exportCampaign = TRUE;
629 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
632 $returnProperties = $campaignReturnProperties;
634 if (isset($exportCampaign)) {
635 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
638 $componentDetails = $headerRows = $sqlColumns = array();
641 $rowCount = self
::EXPORT_ROW_COUNT
;
643 // we write to temp table often to avoid using too much memory
648 // for CRM-3157 purposes
649 $i18n = CRM_Core_I18n
::singleton();
652 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
653 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
658 while ($dao->fetch()) {
662 //convert the pseudo constants
663 $query->convertToPseudoNames($dao);
665 //first loop through returnproperties so that we return what is required, and in same order.
666 $relationshipField = 0;
667 foreach ($returnProperties as $field => $value) {
668 //we should set header only once
671 // Split campaign into 2 fields for id and title
672 if (substr($field, -8) == 'campaign') {
673 $headerRows[] = ts('Campaign Title');
675 elseif (substr($field, -11) == 'campaign_id') {
676 $headerRows[] = ts('Campaign ID');
678 elseif (isset($query->_fields
[$field]['title'])) {
679 $headerRows[] = $query->_fields
[$field]['title'];
681 elseif ($field == 'phone_type_id') {
682 $headerRows[] = ts('Phone Type');
684 elseif ($field == 'provider_id') {
685 $headerRows[] = ts('IM Service Provider');
687 elseif (is_array($value) && $field == 'location') {
688 // fix header for location type case
689 foreach ($value as $ltype => $val) {
690 foreach (array_keys($val) as $fld) {
691 $type = explode('-', $fld);
692 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
694 if (!empty($type[1])) {
695 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
696 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
698 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
699 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
702 $headerRows[] = $hdr;
703 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
708 elseif (substr($field, 0, 5) == 'case_') {
709 if ($query->_fields
['case'][$field]['title']) {
710 $headerRows[] = $query->_fields
['case'][$field]['title'];
712 elseif ($query->_fields
['activity'][$field]['title']) {
713 $headerRows[] = $query->_fields
['activity'][$field]['title'];
716 elseif (array_key_exists($field, $contactRelationshipTypes)) {
718 foreach ($value as $relationField => $relationValue) {
719 // below block is same as primary block (duplicate)
720 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
721 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
722 $headerName = $field . '-' . $relationField;
725 if ($relationField == 'current_employer') {
726 $headerName = $field . '-' . 'current_employer';
729 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
733 $headerRows[] = $headerName;
735 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
737 elseif ($relationField == 'phone_type_id') {
738 $headerName = $field . '-' . 'Phone Type';
739 $headerRows[] = $headerName;
740 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
742 elseif ($relationField == 'provider_id') {
743 $headerName = $field . '-' . 'Im Service Provider';
744 $headerRows[] = $headerName;
745 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
747 elseif ($relationField == 'state_province_id') {
748 $headerName = $field . '-' . 'state_province_id';
749 $headerRows[] = $headerName;
750 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
752 elseif (is_array($relationValue) && $relationField == 'location') {
753 // fix header for location type case
754 foreach ($relationValue as $ltype => $val) {
755 foreach (array_keys($val) as $fld) {
756 $type = explode('-', $fld);
758 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
760 if (!empty($type[1])) {
761 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
762 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
764 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
765 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
768 $headerName = $field . '-' . $hdr;
769 $headerRows[] = $headerName;
770 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
776 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
777 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
780 $headerRows[] = $field;
784 self
::sqlColumnDefn($query, $sqlColumns, $field);
788 // add im_provider to $dao object
789 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
790 $dao->im_provider
= $dao->provider_id
;
793 //build row values (data)
795 if (property_exists($dao, $field)) {
796 $fieldValue = $dao->$field;
797 // to get phone type from phone type id
798 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
799 $fieldValue = $phoneTypes[$fieldValue];
801 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
802 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
804 elseif ($field == 'participant_role_id') {
805 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
806 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
807 $viewRoles = array();
808 foreach (explode($sep, $dao->$field) as $k => $v) {
809 $viewRoles[] = $participantRoles[$v];
811 $fieldValue = implode(',', $viewRoles);
813 elseif ($field == 'master_id') {
814 $masterAddressId = NULL;
815 if (isset($dao->master_id
)) {
816 $masterAddressId = $dao->master_id
;
818 // get display name of contact that address is shared.
819 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $dao->contact_id
);
823 if ($field == 'id') {
824 $row[$field] = $dao->contact_id
;
825 // special case for calculated field
827 elseif ($field == 'source_contact_id') {
828 $row[$field] = $dao->contact_id
;
830 elseif ($field == 'pledge_balance_amount') {
831 $row[$field] = $dao->pledge_amount
- $dao->pledge_total_paid
;
832 // special case for calculated field
834 elseif ($field == 'pledge_next_pay_amount') {
835 $row[$field] = $dao->pledge_next_pay_amount +
$dao->pledge_outstanding_amount
;
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();
1225 * @param $customSearchClass
1226 * @param $formValues
1229 static function exportCustom($customSearchClass, $formValues, $order) {
1230 $ext = CRM_Extension_System
::singleton()->getMapper();
1231 if (!$ext->isExtensionClass($customSearchClass)) {
1232 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php');
1235 require_once ($ext->classToPath($customSearchClass));
1237 $search = new $customSearchClass($formValues);
1239 $includeContactIDs = FALSE;
1240 if ($formValues['radio_ts'] == 'ts_sel') {
1241 $includeContactIDs = TRUE;
1244 $sql = $search->all(0, 0, $order, $includeContactIDs);
1246 $columns = $search->columns();
1248 $header = array_keys($columns);
1249 $fields = array_values($columns);
1252 $dao = CRM_Core_DAO
::executeQuery($sql);
1254 if (method_exists($search, 'alterRow')) {
1257 while ($dao->fetch()) {
1260 foreach ($fields as $field) {
1261 $row[$field] = $dao->$field;
1264 $search->alterRow($row);
1269 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1270 CRM_Utils_System
::civiExit();
1275 * @param $sqlColumns
1278 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1279 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1283 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1284 if ($fieldName == 'id') {
1285 $fieldName = 'civicrm_primary_id';
1288 // early exit for master_id, CRM-12100
1289 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1290 if ($fieldName == 'master_id') {
1291 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1295 // set the sql columns
1296 if (isset($query->_fields
[$field]['type'])) {
1297 switch ($query->_fields
[$field]['type']) {
1298 case CRM_Utils_Type
::T_INT
:
1299 case CRM_Utils_Type
::T_BOOLEAN
:
1300 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1303 case CRM_Utils_Type
::T_STRING
:
1304 if (isset($query->_fields
[$field]['maxlength'])) {
1305 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1308 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1312 case CRM_Utils_Type
::T_TEXT
:
1313 case CRM_Utils_Type
::T_LONGTEXT
:
1314 case CRM_Utils_Type
::T_BLOB
:
1315 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1316 $sqlColumns[$fieldName] = "$fieldName longtext";
1319 case CRM_Utils_Type
::T_FLOAT
:
1320 case CRM_Utils_Type
::T_ENUM
:
1321 case CRM_Utils_Type
::T_DATE
:
1322 case CRM_Utils_Type
::T_TIME
:
1323 case CRM_Utils_Type
::T_TIMESTAMP
:
1324 case CRM_Utils_Type
::T_MONEY
:
1325 case CRM_Utils_Type
::T_EMAIL
:
1326 case CRM_Utils_Type
::T_URL
:
1327 case CRM_Utils_Type
::T_CCNUM
:
1329 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1334 if (substr($fieldName, -3, 3) == '_id') {
1335 // for trxn_id and its variants use a longer buffer
1336 // to accomodate different systems - CRM-13739
1337 static $notRealIDFields = NULL;
1338 if ($notRealIDFields == NULL) {
1339 $notRealIDFields = array( 'trxn_id', 'componentpaymentfield_transaction_id' );
1342 if (in_array($fieldName, $notRealIDFields)) {
1343 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1346 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1350 $changeFields = array(
1356 if (in_array($fieldName, $changeFields)) {
1357 $sqlColumns[$fieldName] = "$fieldName text";
1360 // set the sql columns for custom data
1361 if (isset($query->_fields
[$field]['data_type'])) {
1363 switch ($query->_fields
[$field]['data_type']) {
1365 case 'StateProvince':
1368 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1372 $sqlColumns[$fieldName] = "$fieldName text";
1376 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1381 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1391 * @param $sqlColumns
1393 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1394 if (empty($details)) {
1403 $id = CRM_Core_DAO
::singleValueQuery($sql);
1408 $sqlClause = array();
1410 foreach ($details as $dontCare => $row) {
1412 $valueString = array($id);
1413 foreach ($row as $dontCare => $value) {
1414 if (empty($value)) {
1415 $valueString[] = "''";
1418 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1421 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1424 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1426 $sqlValueString = implode(",\n", $sqlClause);
1429 INSERT INTO $tableName $sqlColumnString
1430 VALUES $sqlValueString
1433 CRM_Core_DAO
::executeQuery($sql);
1437 * @param $sqlColumns
1441 static function createTempTable(&$sqlColumns) {
1442 //creating a temporary table for the search result that need be exported
1443 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1445 // also create the sql table
1446 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1447 CRM_Core_DAO
::executeQuery($sql);
1450 CREATE TABLE {$exportTempTable} (
1451 id int unsigned NOT NULL AUTO_INCREMENT,
1453 $sql .= implode(",\n", array_values($sqlColumns));
1458 // add indexes for street_address and household_name if present
1459 $addIndices = array(
1462 'civicrm_primary_id',
1465 foreach ($addIndices as $index) {
1466 if (isset($sqlColumns[$index])) {
1468 INDEX index_{$index}( $index )
1474 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1477 CRM_Core_DAO
::executeQuery($sql);
1478 return $exportTempTable;
1483 * @param $headerRows
1484 * @param $sqlColumns
1485 * @param $exportParams
1487 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1488 // check if any records are present based on if they have used shared address feature,
1489 // and not based on if city / state .. matches.
1491 SELECT r1.id as copy_id,
1492 r1.civicrm_primary_id as copy_contact_id,
1493 r1.addressee as copy_addressee,
1494 r1.addressee_id as copy_addressee_id,
1495 r1.postal_greeting as copy_postal_greeting,
1496 r1.postal_greeting_id as copy_postal_greeting_id,
1498 r2.civicrm_primary_id as master_contact_id,
1499 r2.postal_greeting as master_postal_greeting,
1500 r2.postal_greeting_id as master_postal_greeting_id,
1501 r2.addressee as master_addressee,
1502 r2.addressee_id as master_addressee_id
1504 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1505 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1507 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1509 // find all the records that have the same street address BUT not in a household
1510 // require match on city and state as well
1512 SELECT r1.id as master_id,
1513 r1.civicrm_primary_id as master_contact_id,
1514 r1.postal_greeting as master_postal_greeting,
1515 r1.postal_greeting_id as master_postal_greeting_id,
1516 r1.addressee as master_addressee,
1517 r1.addressee_id as master_addressee_id,
1519 r2.civicrm_primary_id as copy_contact_id,
1520 r2.postal_greeting as copy_postal_greeting,
1521 r2.postal_greeting_id as copy_postal_greeting_id,
1522 r2.addressee as copy_addressee,
1523 r2.addressee_id as copy_addressee_id
1525 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1526 r1.city = r2.city AND
1527 r1.state_province_id = r2.state_province_id )
1528 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1529 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1530 AND ( r1.street_address != '' )
1534 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1536 // unset ids from $merge already present in $linkedMerge
1537 foreach ($linkedMerge as $masterID => $values) {
1538 $keys = array($masterID);
1539 $keys = array_merge($keys, array_keys($values['copy']));
1540 foreach ($merge as $mid => $vals) {
1541 if (in_array($mid, $keys)) {
1542 unset($merge[$mid]);
1545 foreach ($values['copy'] as $copyId) {
1546 if (in_array($copyId, $keys)) {
1547 unset($merge[$mid]['copy'][$copyId]);
1553 $merge = $merge +
$linkedMerge;
1555 foreach ($merge as $masterID => $values) {
1558 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1561 $params = array(1 => array($values['addressee'], 'String'),
1562 2 => array($values['postalGreeting'], 'String'),
1563 3 => array($values['emailGreeting'], 'String'),
1564 4 => array($masterID, 'Integer'),
1566 CRM_Core_DAO
::executeQuery($sql, $params);
1568 // delete all copies
1569 $deleteIDs = array_keys($values['copy']);
1570 $deleteIDString = implode(',', $deleteIDs);
1572 DELETE FROM $tableName
1573 WHERE id IN ( $deleteIDString )
1575 CRM_Core_DAO
::executeQuery($sql);
1578 // unset temporary columns that were added for postal mailing format
1579 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1580 $unsetKeys = array_keys($sqlColumns);
1581 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1582 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1583 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1591 * @param $exportParams
1595 static function _replaceMergeTokens($contactId, $exportParams) {
1596 $greetings = array();
1599 $greetingFields = array(
1603 foreach ($greetingFields as $greeting) {
1604 if (!empty($exportParams[$greeting])) {
1605 $greetingLabel = $exportParams[$greeting];
1606 if (empty($contact)) {
1611 $contact = civicrm_api('contact', 'get', $values);
1613 if (!empty($contact['is_error'])) {
1616 $contact = $contact['values'][$contact['id']];
1619 $tokens = array('contact' => $greetingLabel);
1620 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1627 * The function unsets static part of the string, if token is the dynamic part.
1628 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1629 * i.e 'Hello Alan' => converted to => 'Alan'
1632 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1633 $addressMergeGreetings, $greetingType = 'postal_greeting'
1635 if (!empty($addressMergeGreetings[$greetingType])) {
1636 $greetingLabel = $addressMergeGreetings[$greetingType];
1638 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1640 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1641 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1642 foreach ($stringsToBeReplaced as $key => $string) {
1643 // to keep one space
1644 $stringsToBeReplaced[$key] = ltrim($string);
1646 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1648 return $parsedString;
1653 * @param $exportParams
1654 * @param bool $sharedAddress
1658 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1659 static $contactGreetingTokens = array();
1661 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1662 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1664 $merge = $parents = array();
1665 $dao = CRM_Core_DAO
::executeQuery($sql);
1667 while ($dao->fetch()) {
1668 $masterID = $dao->master_id
;
1669 $copyID = $dao->copy_id
;
1670 $masterPostalGreeting = $dao->master_postal_greeting
;
1671 $masterAddressee = $dao->master_addressee
;
1672 $copyAddressee = $dao->copy_addressee
;
1674 if (!$sharedAddress) {
1675 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1676 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1678 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1679 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1681 $masterAddressee = CRM_Utils_Array
::value('addressee',
1682 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1685 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1686 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1688 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1689 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1691 $copyAddressee = CRM_Utils_Array
::value('addressee',
1692 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1696 if (!isset($merge[$masterID])) {
1697 // check if this is an intermediate child
1698 // this happens if there are 3 or more matches a,b, c
1699 // the above query will return a, b / a, c / b, c
1700 // we might be doing a bit more work, but for now its ok, unless someone
1701 // knows how to fix the query above
1702 if (isset($parents[$masterID])) {
1703 $masterID = $parents[$masterID];
1706 $merge[$masterID] = array(
1707 'addressee' => $masterAddressee,
1709 'postalGreeting' => $masterPostalGreeting,
1711 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1714 $parents[$copyID] = $masterID;
1716 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1718 if (!empty($exportParams['postal_greeting_other']) &&
1719 count($merge[$masterID]['copy']) >= 1
1721 // use static greetings specified if no of contacts > 2
1722 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1724 elseif ($copyPostalGreeting) {
1725 self
::_trimNonTokens($copyPostalGreeting,
1726 $postalOptions[$dao->copy_postal_greeting_id
],
1729 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1730 // if there happens to be a duplicate, remove it
1731 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1734 if (!empty($exportParams['addressee_other']) &&
1735 count($merge[$masterID]['copy']) >= 1
1737 // use static greetings specified if no of contacts > 2
1738 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1740 elseif ($copyAddressee) {
1741 self
::_trimNonTokens($copyAddressee,
1742 $addresseeOptions[$dao->copy_addressee_id
],
1743 $exportParams, 'addressee'
1745 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1748 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1755 * Function to merge household record into the individual record
1758 * @param string $exportTempTable temporary temp table that stores the records
1759 * @param array $headerRows array of headers for the export file
1760 * @param array $sqlColumns array of names of the table columns of the temp table
1761 * @param string $prefix name of the relationship type that is prefixed to the table columns
1763 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1764 $prefixColumn = $prefix . '_';
1765 $allKeys = array_keys($sqlColumns);
1766 $replaced = array();
1767 $headerRows = array_values($headerRows);
1769 // name map of the non standard fields in header rows & sql columns
1770 $mappingFields = array(
1771 'civicrm_primary_id' => 'id',
1772 'contact_source' => 'source',
1773 'current_employer_id' => 'employer_id',
1774 'contact_is_deleted' => 'is_deleted',
1775 'name' => 'address_name',
1776 'provider_id' => 'im_service_provider',
1777 'phone_type_id' => 'phone_type'
1780 //figure out which columns are to be replaced by which ones
1781 foreach ($sqlColumns as $columnNames => $dontCare) {
1782 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1783 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1786 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1788 if (!empty($sqlColumns[$householdColName])) {
1789 $replaced[$columnNames] = $householdColName;
1793 $query = "UPDATE $exportTempTable SET ";
1796 foreach ($replaced as $from => $to) {
1797 $clause[] = "$from = $to ";
1798 unset($sqlColumns[$to]);
1799 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1800 unset($headerRows[$key]);
1803 $query .= implode(",\n", $clause);
1804 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1806 CRM_Core_DAO
::executeQuery($query);
1808 //drop the table columns that store redundant household info
1809 $dropQuery = "ALTER TABLE $exportTempTable ";
1810 foreach ($replaced as $householdColumns) {
1811 $dropClause[] = " DROP $householdColumns ";
1813 $dropQuery .= implode(",\n", $dropClause);
1815 CRM_Core_DAO
::executeQuery($dropQuery);
1817 // also drop the temp table if exists
1818 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1819 CRM_Core_DAO
::executeQuery($sql);
1821 // clean up duplicate records
1823 CREATE TABLE {$exportTempTable}_temp SELECT *
1824 FROM {$exportTempTable}
1825 GROUP BY civicrm_primary_id ";
1827 CRM_Core_DAO
::executeQuery($query);
1829 $query = "DROP TABLE $exportTempTable";
1830 CRM_Core_DAO
::executeQuery($query);
1832 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1833 CRM_Core_DAO
::executeQuery($query);
1837 * @param $exportTempTable
1838 * @param $headerRows
1839 * @param $sqlColumns
1840 * @param $exportMode
1841 * @param null $saveFile
1842 * @param string $batchItems
1844 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1845 $writeHeader = TRUE;
1847 $limit = self
::EXPORT_ROW_COUNT
;
1849 $query = "SELECT * FROM $exportTempTable";
1852 $limitQuery = $query . "
1853 LIMIT $offset, $limit
1855 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1861 $componentDetails = array();
1862 while ($dao->fetch()) {
1865 foreach ($sqlColumns as $column => $dontCare) {
1866 $row[$column] = $dao->$column;
1868 $componentDetails[] = $row;
1870 if ( $exportMode == 'financial' ) {
1871 $getExportFileName = 'CiviCRM Contribution Search';
1874 $getExportFileName =self
::getExportFileName( 'csv', $exportMode );
1876 $csvRows = CRM_Core_Report_Excel
::writeCSVFile( $getExportFileName,
1883 if ($saveFile && !empty($csvRows)) {
1884 $batchItems .= $csvRows;
1887 $writeHeader = false;
1893 * Function to manipulate header rows for relationship fields
1896 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1897 foreach ($headerRows as & $header) {
1898 $split = explode('-', $header);
1899 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1900 $split[0] = $relationTypeName;
1901 $header = implode('-', $split);
1907 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1908 * or have no street address
1911 static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1912 $whereClause = array();
1914 if (array_key_exists('is_deceased', $sqlColumns)) {
1915 $whereClause[] = 'is_deceased = 1';
1918 if (array_key_exists('do_not_mail', $sqlColumns)) {
1919 $whereClause[] = 'do_not_mail = 1';
1922 if (array_key_exists('street_address', $sqlColumns)) {
1923 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1925 // check for supplemental_address_1
1926 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1927 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1928 'address_options', TRUE, NULL, TRUE
1930 if (!empty($addressOptions['supplemental_address_1'])) {
1931 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1932 // enclose it again, since we are doing an AND in between a set of ORs
1933 $addressWhereClause = "( $addressWhereClause )";
1937 $whereClause[] = $addressWhereClause;
1940 if (!empty($whereClause)) {
1941 $whereClause = implode(' OR ', $whereClause);
1944 FROM $exportTempTable
1945 WHERE {$whereClause}";
1946 CRM_Core_DAO
::singleValueQuery($query);
1949 // unset temporary columns that were added for postal mailing format
1950 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1951 $unsetKeys = array_keys($sqlColumns);
1952 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1953 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1954 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1961 * Build componentPayment fields.
1963 static function componentPaymentFields() {
1964 static $componentPaymentFields;
1965 if (!isset( $componentPaymentFields)) {
1966 $componentPaymentFields = array(
1967 'componentPaymentField_total_amount' => ts('Total Amount'),
1968 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1969 'componentPaymentField_received_date' => ts('Received Date'),
1970 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1971 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1974 return $componentPaymentFields;