3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2013
37 * This class contains the funtions for Component export
40 class CRM_Export_BAO_Export
{
41 // increase this number a lot to avoid making too many queries
42 // LIMIT is not much faster than a no LIMIT query
44 CONST EXPORT_ROW_COUNT
= 10000;
47 * Function to get the list the export fields
49 * @param int $selectAll user preference while export
50 * @param array $ids contact ids
51 * @param array $params associated array of fields
52 * @param string $order order by clause
53 * @param array $fields associated array of fields
54 * @param array $moreReturnProperties additional return fields
55 * @param int $exportMode export mode
56 * @param string $componentClause component clause
57 * @param string $componentTable component table
58 * @param bool $mergeSameAddress merge records if they have same address
59 * @param bool $mergeSameHousehold merge records if they belong to the same household
64 static function exportComponents($selectAll,
69 $moreReturnProperties = NULL,
70 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
71 $componentClause = NULL,
72 $componentTable = NULL,
73 $mergeSameAddress = FALSE,
74 $mergeSameHousehold = FALSE,
75 $exportParams = array(),
76 $queryOperator = 'AND'
78 $headerRows = $returnProperties = array();
79 $primary = $paymentFields = $selectedPaymentFields = FALSE;
80 $origFields = $fields;
81 $queryMode = $relationField = NULL;
83 $allCampaigns = array();
84 $exportCampaign = FALSE;
86 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
87 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
88 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
97 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
99 switch ($exportMode) {
100 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
101 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
104 case CRM_Export_Form_Select
::EVENT_EXPORT
:
105 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
108 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
109 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
112 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
113 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
116 case CRM_Export_Form_Select
::CASE_EXPORT
:
117 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
120 case CRM_Export_Form_Select
::GRANT_EXPORT
:
121 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
124 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
125 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
129 //construct return properties
130 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
131 $locationTypeFields = array(
133 'supplemental_address_1',
134 'supplemental_address_2',
137 'postal_code_suffix',
147 foreach ($fields as $key => $value) {
148 $phoneTypeId = $imProviderId = NULL;
149 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
153 // get phoneType id and IM service provider id seperately
154 if ($fieldName == 'phone') {
155 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
157 elseif ($fieldName == 'im') {
158 $imProviderId = CRM_Utils_Array
::value(3, $value);
160 elseif (substr($fieldName, -8) == 'campaign') {
161 $exportCampaign = TRUE;
164 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
165 if (CRM_Utils_Array
::value(2, $value)) {
166 $relationField = CRM_Utils_Array
::value(2, $value);
167 if (trim(CRM_Utils_Array
::value(3, $value))) {
168 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
171 $relLocTypeId = 'Primary';
174 if ($relationField == 'phone') {
175 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
177 elseif ($relationField == 'im') {
178 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
181 elseif (CRM_Utils_Array
::value(4, $value)) {
182 $relationField = CRM_Utils_Array
::value(4, $value);
183 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
184 if ($relationField == 'phone') {
185 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
187 elseif ($relationField == 'im') {
188 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
193 $contactType = CRM_Utils_Array
::value(0, $value);
194 $locTypeId = CRM_Utils_Array
::value(2, $value);
196 if ($relationField) {
197 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
198 if ($relPhoneTypeId) {
199 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
201 elseif ($relIMProviderId) {
202 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
205 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
207 $relPhoneTypeId = $relIMProviderId = NULL;
210 $returnProperties[$relationshipTypes][$relationField] = 1;
213 elseif (is_numeric($locTypeId)) {
215 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
217 elseif ($imProviderId) {
218 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
221 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
225 //hack to fix component fields
226 if ($fieldName == 'event_id') {
227 $returnProperties['event_title'] = 1;
230 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
231 array_key_exists( $fieldName, self
::componentPaymentFields())
233 $selectedPaymentFields = true;
234 $paymentTableId = 'participant_id';
235 $returnProperties[$fieldName] = 1;
238 $returnProperties[$fieldName] = 1;
240 //campaign field export.
241 if (substr($fieldName, -8) == 'campaign') {
242 $fldNames = explode('_', $fieldName);
243 $returnProperties["{$fldNames[0]}_campaign_id"] = 1;
249 // hack to add default returnproperty based on export mode
250 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
251 $returnProperties['contribution_id'] = 1;
253 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
254 $returnProperties['participant_id'] = 1;
255 if (CRM_Utils_Array
::value('participant_role', $returnProperties)) {
256 unset($returnProperties['participant_role']);
257 $returnProperties['participant_role_id'] = 1;
260 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
261 $returnProperties['membership_id'] = 1;
263 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
264 $returnProperties['pledge_id'] = 1;
266 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
267 $returnProperties['case_id'] = 1;
269 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
270 $returnProperties['grant_id'] = 1;
272 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
273 $returnProperties['activity_id'] = 1;
278 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
279 foreach ($fields as $key => $var) {
280 if ($key && (substr($key, 0, 6) != 'custom')) {
282 $returnProperties[$key] = 1;
287 $returnProperties['location_type'] = 1;
288 $returnProperties['im_provider'] = 1;
289 $returnProperties['phone_type_id'] = 1;
290 $returnProperties['provider_id'] = 1;
291 $returnProperties['current_employer'] = 1;
294 $extraReturnProperties = array();
295 $paymentFields = FALSE;
297 switch ($queryMode) {
298 case CRM_Contact_BAO_Query
::MODE_EVENT
:
299 $paymentFields = TRUE;
300 $paymentTableId = 'participant_id';
303 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
304 $paymentFields = TRUE;
305 $paymentTableId = 'membership_id';
308 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
309 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
310 $paymentFields = TRUE;
311 $paymentTableId = 'pledge_payment_id';
314 case CRM_Contact_BAO_Query
::MODE_CASE
:
315 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
319 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
320 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
322 $campaignReturnProperties = array();;
323 foreach ($componentReturnProperties as $fld => $true) {
324 $campaignReturnProperties[$fld] = $true;
325 if (substr($fld, -11) == 'campaign_id') {
326 $exportCampaign = TRUE;
327 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
330 $componentReturnProperties = $campaignReturnProperties;
332 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
334 if (!empty($extraReturnProperties)) {
335 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
338 // unset non exportable fields for components
339 $nonExpoFields = array(
340 'groups', 'tags', 'notes', 'contribution_status_id',
341 'pledge_status_id', 'pledge_payment_status_id',
343 foreach ($nonExpoFields as $value) {
344 unset($returnProperties[$value]);
349 if ($mergeSameAddress) {
350 //make sure the addressee fields are selected
351 //while using merge same address feature
352 $returnProperties['addressee'] = 1;
353 $returnProperties['postal_greeting'] = 1;
354 $returnProperties['email_greeting'] = 1;
355 $returnProperties['street_name'] = 1;
356 $returnProperties['household_name'] = 1;
357 $returnProperties['street_address'] = 1;
358 $returnProperties['city'] = 1;
359 $returnProperties['state_province'] = 1;
361 // some columns are required for assistance incase they are not already present
362 $exportParams['merge_same_address']['temp_columns'] = array();
363 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
364 foreach ($tempColumns as $column) {
365 if (!array_key_exists($column, $returnProperties)) {
366 $returnProperties[$column] = 1;
367 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
368 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
373 if ($componentTable &&
374 CRM_Utils_Array
::value('additional_group', $exportParams)
376 // If an Additional Group is selected, then all contacts in that group are
377 // added to the export set (filtering out duplicates).
379 INSERT INTO {$componentTable} SELECT distinct gc.contact_id FROM civicrm_group_contact gc WHERE gc.group_id = {$exportParams['additional_group']} ON DUPLICATE KEY UPDATE {$componentTable}.contact_id = gc.contact_id";
380 CRM_Core_DAO
::executeQuery($query);
383 if ($moreReturnProperties) {
385 if (CRM_Utils_Array
::value('group', $moreReturnProperties)) {
386 unset($moreReturnProperties['group']);
387 $moreReturnProperties['groups'] = 1;
389 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
392 $exportParams['postal_mailing_export']['temp_columns'] = array();
393 if ($exportParams['exportOption'] == 2 &&
394 isset($exportParams['postal_mailing_export']) &&
395 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
397 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
398 foreach ($postalColumns as $column) {
399 if (!array_key_exists($column, $returnProperties)) {
400 $returnProperties[$column] = 1;
401 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
406 $query = new CRM_Contact_BAO_Query(NULL, $returnProperties, NULL,
407 FALSE, FALSE, $queryMode,
408 FALSE, TRUE, TRUE, NULL, $queryOperator
411 list($select, $from, $where, $having) = $query->query();
413 if ($mergeSameHousehold == 1) {
414 if (!$returnProperties['id']) {
415 $returnProperties['id'] = 1;
418 //also merge Head of Household
419 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
420 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
422 foreach ($returnProperties as $key => $value) {
423 if (!array_key_exists($key, $contactRelationshipTypes)) {
424 $returnProperties[$relationKeyMOH][$key] = $value;
425 $returnProperties[$relationKeyHOH][$key] = $value;
429 unset($returnProperties[$relationKeyMOH]['location_type']);
430 unset($returnProperties[$relationKeyMOH]['im_provider']);
431 unset($returnProperties[$relationKeyHOH]['location_type']);
432 unset($returnProperties[$relationKeyHOH]['im_provider']);
435 $allRelContactArray = $relationQuery = array();
437 foreach ($contactRelationshipTypes as $rel => $dnt) {
438 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
439 $allRelContactArray[$rel] = array();
440 // build Query for each relationship
441 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
442 NULL, FALSE, FALSE, $queryMode
444 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
446 list($id, $direction) = explode('_', $rel, 2);
447 // identify the relationship direction
448 $contactA = 'contact_id_a';
449 $contactB = 'contact_id_b';
450 if ($direction == 'b_a') {
451 $contactA = 'contact_id_b';
452 $contactB = 'contact_id_a';
454 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
457 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
458 $activityContacts = CRM_Core_PseudoConstant
::activityContacts('name');
459 $sourceID = CRM_Utils_Array
::key('Activity Source', $activityContacts);
460 $query = "SELECT contact_id FROM civicrm_activity_contact
461 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
462 record_type_id = {$sourceID}";
463 $dao = CRM_Core_DAO
::executeQuery($query);
464 while ($dao->fetch()) {
465 $relIDs[] = $dao->contact_id
;
469 switch ($exportMode) {
470 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
471 $component = 'civicrm_contribution';
474 case CRM_Export_Form_Select
::EVENT_EXPORT
:
475 $component = 'civicrm_participant';
478 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
479 $component = 'civicrm_membership';
482 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
483 $component = 'civicrm_pledge';
486 case CRM_Export_Form_Select
::GRANT_EXPORT
:
487 $component = 'civicrm_grant';
491 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
492 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
495 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
499 $relationshipJoin = $relationshipClause = '';
500 if ($componentTable) {
501 $relationshipJoin = " INNER JOIN $componentTable ctTable ON ctTable.contact_id = {$contactA}";
504 $relID = implode(',', $relIDs);
505 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
508 $relationFrom = " {$relationFrom}
509 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
510 {$relationshipJoin} ";
512 //check for active relationship status only
513 $today = date('Ymd');
514 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
515 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
516 $relationGroupBy = " GROUP BY crel.{$contactA}";
517 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
518 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
520 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
521 while ($allRelContactDAO->fetch()) {
522 //FIX Me: Migrate this to table rather than array
523 // build the array of all related contacts
524 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
526 $allRelContactDAO->free();
530 // make sure the groups stuff is included only if specifically specified
531 // by the fields param (CRM-1969), else we limit the contacts outputted to only
532 // ones that are part of a group
533 if (CRM_Utils_Array
::value('groups', $returnProperties)) {
534 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
535 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
536 // total hack for export, CRM-3618
537 $from = str_replace($oldClause,
543 if ($componentTable) {
544 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
546 elseif ($componentClause) {
548 $where = "WHERE $componentClause";
551 $where .= " AND $componentClause";
555 $queryString = "$select $from $where $having";
558 if (CRM_Utils_Array
::value('tags', $returnProperties) ||
559 CRM_Utils_Array
::value('groups', $returnProperties) ||
560 CRM_Utils_Array
::value('notes', $returnProperties) ||
562 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
564 $groupBy = " GROUP BY contact_a.id";
567 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
568 $groupBy = " GROUP BY civicrm_activity.id ";
570 $queryString .= $groupBy;
572 list($field, $dir) = explode(' ', $order, 2);
573 $field = trim($field);
574 if (CRM_Utils_Array
::value($field, $returnProperties)) {
575 // $queryString .= " ORDER BY $order";
579 $multipleSelectFields = array('preferred_communication_method' => 1);
581 $addPaymentHeader = FALSE;
583 $paymentDetails = array();
584 if ($paymentFields ||
$selectedPaymentFields) {
586 // get payment related in for event and members
587 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
588 //get all payment headers.
589 // If we haven't selected specific payment fields, load in all the
591 if (!$selectedPaymentFields) {
592 $paymentHeaders = self
::componentPaymentFields();
593 if (!empty($paymentDetails)) {
594 $addPaymentHeader = TRUE;
597 // If we have seleted specific payment fields, leave the payment headers
598 // as an empty array; the headers for each selected field will be added
601 $paymentHeaders = array();
603 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
607 if ($exportCampaign) {
608 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
611 $componentDetails = $headerRows = $sqlColumns = array();
614 $rowCount = self
::EXPORT_ROW_COUNT
;
616 // we write to temp table often to avoid using too much memory
621 // for CRM-3157 purposes
622 $i18n = CRM_Core_I18n
::singleton();
625 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
626 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
631 while ($dao->fetch()) {
635 //convert the pseudo constants
636 $query->convertToPseudoNames($dao);
638 //first loop through returnproperties so that we return what is required, and in same order.
639 $relationshipField = 0;
640 foreach ($returnProperties as $field => $value) {
641 //we should set header only once
644 if (isset($query->_fields
[$field]['title'])) {
645 $headerRows[] = $query->_fields
[$field]['title'];
647 elseif ($field == 'phone_type_id') {
648 $headerRows[] = ts('Phone Type');
650 elseif ($field == 'provider_id') {
651 $headerRows[] = ts('IM Service Provider');
653 elseif (is_array($value) && $field == 'location') {
654 // fix header for location type case
655 foreach ($value as $ltype => $val) {
656 foreach (array_keys($val) as $fld) {
657 $type = explode('-', $fld);
658 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
660 if (CRM_Utils_Array
::value(1, $type)) {
661 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
662 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
664 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
665 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
668 $headerRows[] = $hdr;
669 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
674 elseif (substr($field, 0, 5) == 'case_') {
675 if ($query->_fields
['case'][$field]['title']) {
676 $headerRows[] = $query->_fields
['case'][$field]['title'];
678 elseif ($query->_fields
['activity'][$field]['title']) {
679 $headerRows[] = $query->_fields
['activity'][$field]['title'];
682 elseif (array_key_exists($field, $contactRelationshipTypes)) {
684 foreach ($value as $relationField => $relationValue) {
685 // below block is same as primary block (duplicate)
686 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
687 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
688 $headerName = $field . '-' . $relationField;
691 if ($relationField == 'current_employer') {
692 $headerName = $field . '-' . 'current_employer';
695 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
699 $headerRows[] = $headerName;
701 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
703 elseif ($relationField == 'phone_type_id') {
704 $headerName = $field . '-' . 'Phone Type';
705 $headerRows[] = $headerName;
706 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
708 elseif ($relationField == 'provider_id') {
709 $headerName = $field . '-' . 'Im Service Provider';
710 $headerRows[] = $headerName;
711 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
713 elseif ($relationField == 'state_province_id') {
714 $headerName = $field . '-' . 'state_province_id';
715 $headerRows[] = $headerName;
716 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
718 elseif (is_array($relationValue) && $relationField == 'location') {
719 // fix header for location type case
720 foreach ($relationValue as $ltype => $val) {
721 foreach (array_keys($val) as $fld) {
722 $type = explode('-', $fld);
724 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
726 if (CRM_Utils_Array
::value(1, $type)) {
727 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
728 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
730 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
731 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
734 $headerName = $field . '-' . $hdr;
735 $headerRows[] = $headerName;
736 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
742 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
743 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
746 $headerRows[] = $field;
750 self
::sqlColumnDefn($query, $sqlColumns, $field);
754 // add im_provider to $dao object
755 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
756 $dao->im_provider
= $dao->provider_id
;
759 //build row values (data)
761 if (property_exists($dao, $field)) {
762 $fieldValue = $dao->$field;
763 // to get phone type from phone type id
764 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
765 $fieldValue = $phoneTypes[$fieldValue];
767 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
768 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
770 elseif ($field == 'participant_role_id') {
771 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
772 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
773 $viewRoles = array();
774 foreach (explode($sep, $dao->$field) as $k => $v) {
775 $viewRoles[] = $participantRoles[$v];
777 $fieldValue = implode(',', $viewRoles);
779 elseif ($field == 'master_id') {
780 $masterAddressId = NULL;
781 if (isset($dao->master_id
)) {
782 $masterAddressId = $dao->master_id
;
784 // get display name of contact that address is shared.
785 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $dao->contact_id
);
789 if ($field == 'id') {
790 $row[$field] = $dao->contact_id
;
791 // special case for calculated field
793 elseif ($field == 'pledge_balance_amount') {
794 $row[$field] = $dao->pledge_amount
- $dao->pledge_total_paid
;
795 // special case for calculated field
797 elseif ($field == 'pledge_next_pay_amount') {
798 $row[$field] = $dao->pledge_next_pay_amount +
$dao->pledge_outstanding_amount
;
800 elseif ($field == 'prefix_id' ||
$field == 'suffix_id' ||
$field == 'gender_id') {
801 if ($field == 'prefix_id') {
802 $row[$field] = $dao->individual_prefix
;
804 elseif ($field == 'suffix_id') {
805 $row[$field] = $dao->individual_suffix
;
808 $row[$field] = $dao->gender
;
811 elseif (is_array($value) && $field == 'location') {
812 // fix header for location type case
813 foreach ($value as $ltype => $val) {
814 foreach (array_keys($val) as $fld) {
815 $type = explode('-', $fld);
816 $fldValue = "{$ltype}-" . $type[0];
818 if (CRM_Utils_Array
::value(1, $type)) {
819 $fldValue .= "-" . $type[1];
822 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
826 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'country'));
829 case 'state_province':
830 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'province'));
834 $imFieldvalue = $fldValue . "-provider_id";
835 $row[$fldValue] = CRM_Utils_Array
::value($dao->$imFieldvalue, $imProviders);
839 $row[$fldValue] = $dao->$fldValue;
845 elseif (array_key_exists($field, $contactRelationshipTypes)) {
846 $relDAO = CRM_Utils_Array
::value($dao->contact_id
, $allRelContactArray[$field]);
847 foreach ($value as $relationField => $relationValue) {
848 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
849 $fieldValue = $relDAO->$relationField;
850 if ($relationField == 'phone_type_id') {
851 $fieldValue = $phoneTypes[$relationValue];
853 elseif ($relationField == 'provider_id') {
854 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
860 $field = $field . '_';
861 if (is_object($relDAO) && $relationField == 'id') {
862 $row[$field . $relationField] = $relDAO->contact_id
;
863 } else if ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
864 foreach ($relationValue as $ltype => $val) {
865 foreach (array_keys($val) as $fld) {
866 $type = explode('-', $fld);
867 $fldValue = "{$ltype}-" . $type[0];
868 if (CRM_Utils_Array
::value(1, $type)) {
869 $fldValue .= "-" . $type[1];
871 // CRM-3157: localise country, region (both have ‘country’ context)
872 // and state_province (‘province’ context)
874 case (!is_object($relDAO)):
875 $row[$field . '_' . $fldValue] = '';
878 case in_array('country', $type):
879 case in_array('world_region', $type):
880 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
881 array('context' => 'country')
885 case in_array('state_province', $type):
886 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
887 array('context' => 'province')
892 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
898 elseif (isset($fieldValue) && $fieldValue != '') {
899 //check for custom data
900 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
901 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
902 $relationQuery[$field]->_options
905 elseif (in_array($relationField, array(
906 'email_greeting', 'postal_greeting', 'addressee'))) {
907 //special case for greeting replacement
908 $fldValue = "{$relationField}_display";
909 $row[$field . $relationField] = $relDAO->$fldValue;
912 //normal relationship fields
913 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
914 switch ($relationField) {
917 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
920 case 'state_province':
921 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
925 $row[$field . $relationField] = $fieldValue;
931 // if relation field is empty or null
932 $row[$field . $relationField] = '';
936 elseif (isset($fieldValue) &&
939 //check for custom data
940 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
941 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
943 elseif (array_key_exists($field, $multipleSelectFields)) {
945 $paramsNew = array($field => $fieldValue);
946 if ($field == 'test_tutoring') {
947 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
950 elseif (substr($field, 0, 4) == 'cmr_') {
951 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
954 $name = array($field => array('newName' => $field, 'groupName' => $field));
956 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
957 $row[$field] = $paramsNew[$field];
959 elseif (in_array($field, array(
960 'email_greeting', 'postal_greeting', 'addressee'))) {
961 //special case for greeting replacement
962 $fldValue = "{$field}_display";
963 $row[$field] = $dao->$fldValue;
966 //normal fields with a touch of CRM-3157
970 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
973 case 'state_province':
974 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
978 case 'preferred_communication_method':
979 case 'preferred_mail_format':
980 $row[$field] = $i18n->crm_translate($fieldValue);
984 $row[$field] = $fieldValue;
989 elseif (substr($field, -8) == 'campaign') {
990 $campIdFld = "{$field}_id";
991 $row[$field] = CRM_Utils_Array
::value($dao->$campIdFld, $allCampaigns, '');
993 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
994 $paymentData = CRM_Utils_Array
::value($dao->$paymentTableId, $paymentDetails);
995 $payFieldMapper = array(
996 'componentPaymentField_total_amount' => 'total_amount',
997 'componentPaymentField_contribution_status' => 'contribution_status',
998 'componentPaymentField_payment_instrument' => 'pay_instru',
999 'componentPaymentField_transaction_id' => 'trxn_id',
1000 'componentPaymentField_received_date' => 'receive_date',
1002 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1005 // if field is empty or null
1010 // add payment headers if required
1011 if ($addPaymentHeader && $paymentFields) {
1012 $headerRows = array_merge($headerRows, $paymentHeaders);
1013 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1014 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1019 $exportTempTable = self
::createTempTable($sqlColumns);
1022 //build header only once
1025 // If specific payment fields have been selected for export, payment
1026 // data will already be in $row. Otherwise, add payment related
1027 // information, if appropriate.
1028 if ($addPaymentHeader) {
1029 if (!$selectedPaymentFields) {
1030 if ($paymentFields) {
1031 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1032 if (!is_array($paymentData) ||
empty($paymentData)) {
1033 $paymentData = $nullContributionDetails;
1035 $row = array_merge($row, $paymentData);
1037 elseif (!empty($paymentDetails)) {
1038 $row = array_merge($row, $nullContributionDetails);
1042 //remove organization name for individuals if it is set for current employer
1043 if (CRM_Utils_Array
::value('contact_type', $row) &&
1044 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1046 $row['organization_name'] = '';
1049 // add component info
1050 // write the row to a file
1051 $componentDetails[] = $row;
1053 // output every $tempRowCount rows
1054 if ($count %
$tempRowCount == 0) {
1055 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1056 $componentDetails = array();
1060 $offset +
= $rowCount;
1063 if ($exportTempTable) {
1064 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1066 // do merge same address and merge same household processing
1067 if ($mergeSameAddress) {
1068 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1071 // merge the records if they have corresponding households
1072 if ($mergeSameHousehold) {
1073 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1074 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1077 // fix the headers for rows with relationship type
1078 if (!empty($relName)) {
1079 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1082 // if postalMailing option is checked, exclude contacts who are deceased, have
1083 // "Do not mail" privacy setting, or have no street address
1084 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1085 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1087 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1091 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1093 // now write the CSV file
1094 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1096 // delete the export temp table and component table
1097 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1098 CRM_Core_DAO
::executeQuery($sql);
1100 CRM_Utils_System
::civiExit();
1103 CRM_Core_Error
::fatal(ts('No records to export'));
1108 * name of the export file based on mode
1110 * @param string $output type of output
1111 * @param int $mode export mode
1113 * @return string name of the file
1115 static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1117 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1118 return ts('CiviCRM Contact Search');
1120 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1121 return ts('CiviCRM Contribution Search');
1123 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1124 return ts('CiviCRM Member Search');
1126 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1127 return ts('CiviCRM Participant Search');
1129 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1130 return ts('CiviCRM Pledge Search');
1132 case CRM_Export_Form_Select
::CASE_EXPORT
:
1133 return ts('CiviCRM Case Search');
1135 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1136 return ts('CiviCRM Grant Search');
1138 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1139 return ts('CiviCRM Activity Search');
1144 * Function to handle import error file creation.
1148 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1149 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1150 if (empty($parserName) ||
empty($type)) {
1154 // clean and ensure parserName is a valid string
1155 $parserName = CRM_Utils_String
::munge($parserName);
1156 $parserClass = explode('_', $parserName);
1158 // make sure parserClass is in the CRM namespace and
1159 // at least 3 levels deep
1160 if ($parserClass[0] == 'CRM' &&
1161 count($parserClass) >= 3
1163 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php");
1164 // ensure the functions exists
1165 if (method_exists($parserName, 'errorFileName') &&
1166 method_exists($parserName, 'saveFileName')
1168 $errorFileName = $parserName::errorFileName($type);
1169 $saveFileName = $parserName::saveFileName($type);
1170 if (!empty($errorFileName) && !empty($saveFileName)) {
1171 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1172 header('Content-Description: File Transfer');
1173 header('Content-Type: text/csv');
1174 header('Content-Length: ' . filesize($errorFileName));
1175 header('Content-Disposition: attachment; filename=' . $saveFileName);
1177 readfile($errorFileName);
1181 CRM_Utils_System
::civiExit();
1184 function exportCustom($customSearchClass, $formValues, $order) {
1185 $ext = CRM_Extension_System
::singleton()->getMapper();
1186 if (!$ext->isExtensionClass($customSearchClass)) {
1187 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php');
1190 require_once ($ext->classToPath($customSearchClass));
1192 $search = new $customSearchClass($formValues);
1194 $includeContactIDs = FALSE;
1195 if ($formValues['radio_ts'] == 'ts_sel') {
1196 $includeContactIDs = TRUE;
1199 $sql = $search->all(0, 0, $order, $includeContactIDs);
1201 $columns = $search->columns();
1203 $header = array_keys($columns);
1204 $fields = array_values($columns);
1207 $dao = CRM_Core_DAO
::executeQuery($sql);
1209 if (method_exists($search, 'alterRow')) {
1212 while ($dao->fetch()) {
1215 foreach ($fields as $field) {
1216 $row[$field] = $dao->$field;
1219 $search->alterRow($row);
1224 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1225 CRM_Utils_System
::civiExit();
1228 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1229 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1233 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1234 if ($fieldName == 'id') {
1235 $fieldName = 'civicrm_primary_id';
1238 // early exit for master_id, CRM-12100
1239 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1240 if ($fieldName == 'master_id') {
1241 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1245 // set the sql columns
1246 if (isset($query->_fields
[$field]['type'])) {
1247 switch ($query->_fields
[$field]['type']) {
1248 case CRM_Utils_Type
::T_INT
:
1249 case CRM_Utils_Type
::T_BOOLEAN
:
1250 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1253 case CRM_Utils_Type
::T_STRING
:
1254 if (isset($query->_fields
[$field]['maxlength'])) {
1255 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1258 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1262 case CRM_Utils_Type
::T_TEXT
:
1263 case CRM_Utils_Type
::T_LONGTEXT
:
1264 case CRM_Utils_Type
::T_BLOB
:
1265 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1266 $sqlColumns[$fieldName] = "$fieldName longtext";
1269 case CRM_Utils_Type
::T_FLOAT
:
1270 case CRM_Utils_Type
::T_ENUM
:
1271 case CRM_Utils_Type
::T_DATE
:
1272 case CRM_Utils_Type
::T_TIME
:
1273 case CRM_Utils_Type
::T_TIMESTAMP
:
1274 case CRM_Utils_Type
::T_MONEY
:
1275 case CRM_Utils_Type
::T_EMAIL
:
1276 case CRM_Utils_Type
::T_URL
:
1277 case CRM_Utils_Type
::T_CCNUM
:
1279 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1284 if (substr($fieldName, -3, 3) == '_id') {
1285 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1288 $changeFields = array(
1294 if (in_array($fieldName, $changeFields)) {
1295 $sqlColumns[$fieldName] = "$fieldName text";
1298 // set the sql columns for custom data
1299 if (isset($query->_fields
[$field]['data_type'])) {
1301 switch ($query->_fields
[$field]['data_type']) {
1303 case 'StateProvince':
1306 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1310 $sqlColumns[$fieldName] = "$fieldName text";
1314 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1319 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1326 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1327 if (empty($details)) {
1336 $id = CRM_Core_DAO
::singleValueQuery($sql);
1341 $sqlClause = array();
1343 foreach ($details as $dontCare => $row) {
1345 $valueString = array($id);
1346 foreach ($row as $dontCare => $value) {
1347 if (empty($value)) {
1348 $valueString[] = "''";
1351 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1354 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1357 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1359 $sqlValueString = implode(",\n", $sqlClause);
1362 INSERT INTO $tableName $sqlColumnString
1363 VALUES $sqlValueString
1366 CRM_Core_DAO
::executeQuery($sql);
1369 static function createTempTable(&$sqlColumns) {
1370 //creating a temporary table for the search result that need be exported
1371 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1373 // also create the sql table
1374 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1375 CRM_Core_DAO
::executeQuery($sql);
1378 CREATE TABLE {$exportTempTable} (
1379 id int unsigned NOT NULL AUTO_INCREMENT,
1381 $sql .= implode(",\n", array_values($sqlColumns));
1386 // add indexes for street_address and household_name if present
1387 $addIndices = array(
1390 'civicrm_primary_id',
1393 foreach ($addIndices as $index) {
1394 if (isset($sqlColumns[$index])) {
1396 INDEX index_{$index}( $index )
1402 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1405 CRM_Core_DAO
::executeQuery($sql);
1406 return $exportTempTable;
1409 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1410 // check if any records are present based on if they have used shared address feature,
1411 // and not based on if city / state .. matches.
1413 SELECT r1.id as copy_id,
1414 r1.civicrm_primary_id as copy_contact_id,
1415 r1.addressee as copy_addressee,
1416 r1.addressee_id as copy_addressee_id,
1417 r1.postal_greeting as copy_postal_greeting,
1418 r1.postal_greeting_id as copy_postal_greeting_id,
1420 r2.civicrm_primary_id as master_contact_id,
1421 r2.postal_greeting as master_postal_greeting,
1422 r2.postal_greeting_id as master_postal_greeting_id,
1423 r2.addressee as master_addressee,
1424 r2.addressee_id as master_addressee_id
1426 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1427 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1429 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1431 // find all the records that have the same street address BUT not in a household
1432 // require match on city and state as well
1434 SELECT r1.id as master_id,
1435 r1.civicrm_primary_id as master_contact_id,
1436 r1.postal_greeting as master_postal_greeting,
1437 r1.postal_greeting_id as master_postal_greeting_id,
1438 r1.addressee as master_addressee,
1439 r1.addressee_id as master_addressee_id,
1441 r2.civicrm_primary_id as copy_contact_id,
1442 r2.postal_greeting as copy_postal_greeting,
1443 r2.postal_greeting_id as copy_postal_greeting_id,
1444 r2.addressee as copy_addressee,
1445 r2.addressee_id as copy_addressee_id
1447 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1448 r1.city = r2.city AND
1449 r1.state_province_id = r2.state_province_id )
1450 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1451 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1452 AND ( r1.street_address != '' )
1456 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1458 // unset ids from $merge already present in $linkedMerge
1459 foreach ($linkedMerge as $masterID => $values) {
1460 $keys = array($masterID);
1461 $keys = array_merge($keys, array_keys($values['copy']));
1462 foreach ($merge as $mid => $vals) {
1463 if (in_array($mid, $keys)) {
1464 unset($merge[$mid]);
1467 foreach ($values['copy'] as $copyId) {
1468 if (in_array($copyId, $keys)) {
1469 unset($merge[$mid]['copy'][$copyId]);
1475 $merge = $merge +
$linkedMerge;
1477 foreach ($merge as $masterID => $values) {
1480 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1483 $params = array(1 => array($values['addressee'], 'String'),
1484 2 => array($values['postalGreeting'], 'String'),
1485 3 => array($values['emailGreeting'], 'String'),
1486 4 => array($masterID, 'Integer'),
1488 CRM_Core_DAO
::executeQuery($sql, $params);
1490 // delete all copies
1491 $deleteIDs = array_keys($values['copy']);
1492 $deleteIDString = implode(',', $deleteIDs);
1494 DELETE FROM $tableName
1495 WHERE id IN ( $deleteIDString )
1497 CRM_Core_DAO
::executeQuery($sql);
1500 // unset temporary columns that were added for postal mailing format
1501 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1502 $unsetKeys = array_keys($sqlColumns);
1503 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1504 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1505 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1511 static function _replaceMergeTokens($contactId, $exportParams) {
1512 $greetings = array();
1515 $greetingFields = array(
1519 foreach ($greetingFields as $greeting) {
1520 if (CRM_Utils_Array
::value($greeting, $exportParams)) {
1521 $greetingLabel = $exportParams[$greeting];
1522 if (empty($contact)) {
1527 $contact = civicrm_api('contact', 'get', $values);
1529 if (CRM_Utils_Array
::value('is_error', $contact)) {
1532 $contact = $contact['values'][$contact['id']];
1535 $tokens = array('contact' => $greetingLabel);
1536 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1543 * The function unsets static part of the string, if token is the dynamic part.
1544 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1545 * i.e 'Hello Alan' => converted to => 'Alan'
1548 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1549 $addressMergeGreetings, $greetingType = 'postal_greeting'
1551 if (CRM_Utils_Array
::value($greetingType, $addressMergeGreetings)) {
1552 $greetingLabel = $addressMergeGreetings[$greetingType];
1554 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1556 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1557 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1558 foreach ($stringsToBeReplaced as $key => $string) {
1559 // to keep one space
1560 $stringsToBeReplaced[$key] = ltrim($string);
1562 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1564 return $parsedString;
1567 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1568 static $contactGreetingTokens = array();
1570 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1571 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1573 $merge = $parents = array();
1574 $dao = CRM_Core_DAO
::executeQuery($sql);
1576 while ($dao->fetch()) {
1577 $masterID = $dao->master_id
;
1578 $copyID = $dao->copy_id
;
1579 $masterPostalGreeting = $dao->master_postal_greeting
;
1580 $masterAddressee = $dao->master_addressee
;
1581 $copyAddressee = $dao->copy_addressee
;
1583 if (!$sharedAddress) {
1584 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1585 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1587 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1588 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1590 $masterAddressee = CRM_Utils_Array
::value('addressee',
1591 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1594 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1595 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1597 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1598 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1600 $copyAddressee = CRM_Utils_Array
::value('addressee',
1601 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1605 if (!isset($merge[$masterID])) {
1606 // check if this is an intermediate child
1607 // this happens if there are 3 or more matches a,b, c
1608 // the above query will return a, b / a, c / b, c
1609 // we might be doing a bit more work, but for now its ok, unless someone
1610 // knows how to fix the query above
1611 if (isset($parents[$masterID])) {
1612 $masterID = $parents[$masterID];
1615 $merge[$masterID] = array(
1616 'addressee' => $masterAddressee,
1618 'postalGreeting' => $masterPostalGreeting,
1620 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1623 $parents[$copyID] = $masterID;
1625 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1627 if (CRM_Utils_Array
::value('postal_greeting_other', $exportParams) &&
1628 count($merge[$masterID]['copy']) >= 1
1630 // use static greetings specified if no of contacts > 2
1631 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1633 elseif ($copyPostalGreeting) {
1634 self
::_trimNonTokens($copyPostalGreeting,
1635 $postalOptions[$dao->copy_postal_greeting_id
],
1638 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1639 // if there happens to be a duplicate, remove it
1640 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1643 if (CRM_Utils_Array
::value('addressee_other', $exportParams) &&
1644 count($merge[$masterID]['copy']) >= 1
1646 // use static greetings specified if no of contacts > 2
1647 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1649 elseif ($copyAddressee) {
1650 self
::_trimNonTokens($copyAddressee,
1651 $addresseeOptions[$dao->copy_addressee_id
],
1652 $exportParams, 'addressee'
1654 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1657 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1664 * Function to merge household record into the individual record
1667 * @param string $exportTempTable temporary temp table that stores the records
1668 * @param array $headerRows array of headers for the export file
1669 * @param array $sqlColumns array of names of the table columns of the temp table
1670 * @param string $prefix name of the relationship type that is prefixed to the table columns
1672 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1673 $prefixColumn = $prefix . '_';
1674 $allKeys = array_keys($sqlColumns);
1675 $replaced = array();
1676 $headerRows = array_values($headerRows);
1678 // name map of the non standard fields in header rows & sql columns
1679 $mappingFields = array(
1680 'civicrm_primary_id' => 'id',
1681 'contact_source' => 'source',
1682 'current_employer_id' => 'employer_id',
1683 'contact_is_deleted' => 'is_deleted',
1684 'name' => 'address_name',
1685 'provider_id' => 'im_service_provider',
1686 'phone_type_id' => 'phone_type'
1689 //figure out which columns are to be replaced by which ones
1690 foreach ($sqlColumns as $columnNames => $dontCare) {
1691 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1692 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1695 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1697 if (CRM_Utils_Array
::value($householdColName, $sqlColumns)) {
1698 $replaced[$columnNames] = $householdColName;
1702 $query = "UPDATE $exportTempTable SET ";
1705 foreach ($replaced as $from => $to) {
1706 $clause[] = "$from = $to ";
1707 unset($sqlColumns[$to]);
1708 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1709 unset($headerRows[$key]);
1712 $query .= implode(",\n", $clause);
1713 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1715 CRM_Core_DAO
::executeQuery($query);
1717 //drop the table columns that store redundant household info
1718 $dropQuery = "ALTER TABLE $exportTempTable ";
1719 foreach ($replaced as $householdColumns) {
1720 $dropClause[] = " DROP $householdColumns ";
1722 $dropQuery .= implode(",\n", $dropClause);
1724 CRM_Core_DAO
::executeQuery($dropQuery);
1726 // also drop the temp table if exists
1727 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1728 CRM_Core_DAO
::executeQuery($sql);
1730 // clean up duplicate records
1732 CREATE TABLE {$exportTempTable}_temp SELECT *
1733 FROM {$exportTempTable}
1734 GROUP BY civicrm_primary_id ";
1736 CRM_Core_DAO
::executeQuery($query);
1738 $query = "DROP TABLE $exportTempTable";
1739 CRM_Core_DAO
::executeQuery($query);
1741 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1742 CRM_Core_DAO
::executeQuery($query);
1745 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1746 $writeHeader = TRUE;
1748 $limit = self
::EXPORT_ROW_COUNT
;
1750 $query = "SELECT * FROM $exportTempTable";
1753 $limitQuery = $query . "
1754 LIMIT $offset, $limit
1756 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1762 $componentDetails = array();
1763 while ($dao->fetch()) {
1766 foreach ($sqlColumns as $column => $dontCare) {
1767 $row[$column] = $dao->$column;
1769 $componentDetails[] = $row;
1771 if ( $exportMode == 'financial' ) {
1772 $getExportFileName = 'CiviCRM Contribution Search';
1775 $getExportFileName =self
::getExportFileName( 'csv', $exportMode );
1777 $csvRows = CRM_Core_Report_Excel
::writeCSVFile( $getExportFileName,
1784 if ($saveFile && !empty($csvRows)) {
1785 $batchItems .= $csvRows;
1788 $writeHeader = false;
1794 * Function to manipulate header rows for relationship fields
1797 function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1798 foreach ($headerRows as & $header) {
1799 $split = explode('-', $header);
1800 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1801 $split[0] = $relationTypeName;
1802 $header = implode('-', $split);
1808 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1809 * or have no street address
1812 function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1813 $whereClause = array();
1815 if (array_key_exists('is_deceased', $sqlColumns)) {
1816 $whereClause[] = 'is_deceased = 1';
1819 if (array_key_exists('do_not_mail', $sqlColumns)) {
1820 $whereClause[] = 'do_not_mail = 1';
1823 if (array_key_exists('street_address', $sqlColumns)) {
1824 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1826 // check for supplemental_address_1
1827 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1828 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1829 'address_options', TRUE, NULL, TRUE
1831 if (CRM_Utils_Array
::value('supplemental_address_1', $addressOptions)) {
1832 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1833 // enclose it again, since we are doing an AND in between a set of ORs
1834 $addressWhereClause = "( $addressWhereClause )";
1838 $whereClause[] = $addressWhereClause;
1841 if (!empty($whereClause)) {
1842 $whereClause = implode(' OR ', $whereClause);
1845 FROM $exportTempTable
1846 WHERE {$whereClause}";
1847 CRM_Core_DAO
::singleValueQuery($query);
1850 // unset temporary columns that were added for postal mailing format
1851 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1852 $unsetKeys = array_keys($sqlColumns);
1853 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1854 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1855 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1862 * Build componentPayment fields.
1864 static function componentPaymentFields() {
1865 static $componentPaymentFields;
1866 if (!isset( $componentPaymentFields)) {
1867 $componentPaymentFields = array(
1868 'componentPaymentField_total_amount' => ts('Total Amount'),
1869 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1870 'componentPaymentField_received_date' => ts('Received Date'),
1871 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1872 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1875 return $componentPaymentFields;