3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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 * Get Querymode based on ExportMode
49 * @param int $exportMode
52 * return string Querymode
54 public function getQueryMode($exportMode) {
55 switch ($exportMode) {
56 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
57 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
60 case CRM_Export_Form_Select
::EVENT_EXPORT
:
61 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
64 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
65 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
68 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
69 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
72 case CRM_Export_Form_Select
::CASE_EXPORT
:
73 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
76 case CRM_Export_Form_Select
::GRANT_EXPORT
:
77 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
80 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
81 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
88 * Get default return property for export based on mode
90 * @param int $exportMode
92 * return returnProperties
94 function defultReturnProperty($exportMode) {
95 // hack to add default returnproperty based on export mode
96 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
97 $returnProperties['contribution_id'] = 1;
99 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
100 $returnProperties['participant_id'] = 1;
101 if (!empty($returnProperties['participant_role'])) {
102 unset($returnProperties['participant_role']);
103 $returnProperties['participant_role_id'] = 1;
106 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
107 $returnProperties['membership_id'] = 1;
109 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
110 $returnProperties['pledge_id'] = 1;
112 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
113 $returnProperties['case_id'] = 1;
115 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
116 $returnProperties['grant_id'] = 1;
118 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
119 $returnProperties['activity_id'] = 1;
121 return $returnProperties;
125 * Get Export component
127 * @param int $exportMode
130 * return string component
132 public function exportComponent($exportMode) {
133 switch ($exportMode) {
134 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
135 $component = 'civicrm_contribution';
138 case CRM_Export_Form_Select
::EVENT_EXPORT
:
139 $component = 'civicrm_participant';
142 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
143 $component = 'civicrm_membership';
146 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
147 $component = 'civicrm_pledge';
150 case CRM_Export_Form_Select
::GRANT_EXPORT
:
151 $component = 'civicrm_grant';
158 * Get the list the export fields.
160 * @param int $selectAll
161 * User preference while export.
164 * @param array $params
165 * Associated array of fields.
166 * @param string $order
168 * @param array $fields
169 * Associated array of fields.
170 * @param array $moreReturnProperties
171 * Additional return fields.
172 * @param int $exportMode
174 * @param string $componentClause
176 * @param string $componentTable
178 * @param bool $mergeSameAddress
179 * Merge records if they have same address.
180 * @param bool $mergeSameHousehold
181 * Merge records if they belong to the same household.
183 * @param array $exportParams
184 * @param string $queryOperator
187 public static function exportComponents(
193 $moreReturnProperties = NULL,
194 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
195 $componentClause = NULL,
196 $componentTable = NULL,
197 $mergeSameAddress = FALSE,
198 $mergeSameHousehold = FALSE,
199 $exportParams = array(),
200 $queryOperator = 'AND'
202 $headerRows = $returnProperties = array();
203 $primary = $paymentFields = $selectedPaymentFields = FALSE;
204 $origFields = $fields;
205 $relationField = NULL;
207 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
208 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
209 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
218 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
220 $queryMode = self
::getQueryMode($exportMode);
223 //construct return properties
224 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
225 $locationTypeFields = array(
227 'supplemental_address_1',
228 'supplemental_address_2',
231 'postal_code_suffix',
241 foreach ($fields as $key => $value) {
242 $phoneTypeId = $imProviderId = NULL;
243 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
247 // get phoneType id and IM service provider id separately
248 if ($fieldName == 'phone') {
249 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
251 elseif ($fieldName == 'im') {
252 $imProviderId = CRM_Utils_Array
::value(3, $value);
255 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
256 if (!empty($value[2])) {
257 $relationField = CRM_Utils_Array
::value(2, $value);
258 if (trim(CRM_Utils_Array
::value(3, $value))) {
259 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
262 $relLocTypeId = 'Primary';
265 if ($relationField == 'phone') {
266 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
268 elseif ($relationField == 'im') {
269 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
272 elseif (!empty($value[4])) {
273 $relationField = CRM_Utils_Array
::value(4, $value);
274 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
275 if ($relationField == 'phone') {
276 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
278 elseif ($relationField == 'im') {
279 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
284 $contactType = CRM_Utils_Array
::value(0, $value);
285 $locTypeId = CRM_Utils_Array
::value(2, $value);
287 if ($relationField) {
288 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
289 if ($relPhoneTypeId) {
290 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
292 elseif ($relIMProviderId) {
293 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
296 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
298 $relPhoneTypeId = $relIMProviderId = NULL;
301 $returnProperties[$relationshipTypes][$relationField] = 1;
304 elseif (is_numeric($locTypeId)) {
306 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
308 elseif ($imProviderId) {
309 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
312 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
316 //hack to fix component fields
317 //revert mix of event_id and title
318 if ($fieldName == 'event_id') {
319 $returnProperties['event_id'] = 1;
322 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
323 array_key_exists($fieldName, self
::componentPaymentFields())
325 $selectedPaymentFields = TRUE;
326 $paymentTableId = 'participant_id';
327 $returnProperties[$fieldName] = 1;
330 $returnProperties[$fieldName] = 1;
334 self
::defultReturnProperty($exportMode);
337 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
338 foreach ($fields as $key => $var) {
339 if ($key && (substr($key, 0, 6) != 'custom')) {
341 $returnProperties[$key] = 1;
346 $returnProperties['location_type'] = 1;
347 $returnProperties['im_provider'] = 1;
348 $returnProperties['phone_type_id'] = 1;
349 $returnProperties['provider_id'] = 1;
350 $returnProperties['current_employer'] = 1;
353 $extraReturnProperties = array();
354 $paymentFields = FALSE;
356 switch ($queryMode) {
357 case CRM_Contact_BAO_Query
::MODE_EVENT
:
358 $paymentFields = TRUE;
359 $paymentTableId = 'participant_id';
362 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
363 $paymentFields = TRUE;
364 $paymentTableId = 'membership_id';
367 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
368 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
369 $paymentFields = TRUE;
370 $paymentTableId = 'pledge_payment_id';
373 case CRM_Contact_BAO_Query
::MODE_CASE
:
374 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
378 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
379 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
380 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
381 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
382 $componentReturnProperties = array_merge(
383 $componentReturnProperties,
384 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
386 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
388 if (!empty($extraReturnProperties)) {
389 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
392 // unset non exportable fields for components
393 $nonExpoFields = array(
397 'contribution_status_id',
399 'pledge_payment_status_id',
401 foreach ($nonExpoFields as $value) {
402 unset($returnProperties[$value]);
407 if ($mergeSameAddress) {
408 //make sure the addressee fields are selected
409 //while using merge same address feature
410 $returnProperties['addressee'] = 1;
411 $returnProperties['postal_greeting'] = 1;
412 $returnProperties['email_greeting'] = 1;
413 $returnProperties['street_name'] = 1;
414 $returnProperties['household_name'] = 1;
415 $returnProperties['street_address'] = 1;
416 $returnProperties['city'] = 1;
417 $returnProperties['state_province'] = 1;
419 // some columns are required for assistance incase they are not already present
420 $exportParams['merge_same_address']['temp_columns'] = array();
421 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
422 foreach ($tempColumns as $column) {
423 if (!array_key_exists($column, $returnProperties)) {
424 $returnProperties[$column] = 1;
425 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
426 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
431 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
432 // If an Additional Group is selected, then all contacts in that group are
433 // added to the export set (filtering out duplicates).
435 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";
436 CRM_Core_DAO
::executeQuery($query);
439 if ($moreReturnProperties) {
441 if (!empty($moreReturnProperties['group'])) {
442 unset($moreReturnProperties['group']);
443 $moreReturnProperties['groups'] = 1;
445 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
448 $exportParams['postal_mailing_export']['temp_columns'] = array();
449 if ($exportParams['exportOption'] == 2 &&
450 isset($exportParams['postal_mailing_export']) &&
451 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
453 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
454 foreach ($postalColumns as $column) {
455 if (!array_key_exists($column, $returnProperties)) {
456 $returnProperties[$column] = 1;
457 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
462 // rectify params to what proximity search expects if there is a value for prox_distance
464 if (!empty($params)) {
465 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
468 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
469 FALSE, FALSE, $queryMode,
470 FALSE, TRUE, TRUE, NULL, $queryOperator
475 $query->_sort
= $order;
476 list($select, $from, $where, $having) = $query->query();
478 if ($mergeSameHousehold == 1) {
479 if (!$returnProperties['id']) {
480 $returnProperties['id'] = 1;
483 //also merge Head of Household
484 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
485 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
487 foreach ($returnProperties as $key => $value) {
488 if (!array_key_exists($key, $contactRelationshipTypes)) {
489 $returnProperties[$relationKeyMOH][$key] = $value;
490 $returnProperties[$relationKeyHOH][$key] = $value;
494 unset($returnProperties[$relationKeyMOH]['location_type']);
495 unset($returnProperties[$relationKeyMOH]['im_provider']);
496 unset($returnProperties[$relationKeyHOH]['location_type']);
497 unset($returnProperties[$relationKeyHOH]['im_provider']);
500 $allRelContactArray = $relationQuery = array();
502 foreach ($contactRelationshipTypes as $rel => $dnt) {
503 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
504 $allRelContactArray[$rel] = array();
505 // build Query for each relationship
506 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
507 NULL, FALSE, FALSE, $queryMode
509 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
511 list($id, $direction) = explode('_', $rel, 2);
512 // identify the relationship direction
513 $contactA = 'contact_id_a';
514 $contactB = 'contact_id_b';
515 if ($direction == 'b_a') {
516 $contactA = 'contact_id_b';
517 $contactB = 'contact_id_a';
519 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
522 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
523 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
524 $query = "SELECT contact_id FROM civicrm_activity_contact
525 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
526 record_type_id = {$sourceID}";
527 $dao = CRM_Core_DAO
::executeQuery($query);
528 while ($dao->fetch()) {
529 $relIDs[] = $dao->contact_id
;
533 self
::exportComponent($exportMode);
535 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
536 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
539 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
543 $relationshipJoin = $relationshipClause = '';
544 if (!$selectAll && $componentTable) {
545 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
547 elseif (!empty($relIDs)) {
548 $relID = implode(',', $relIDs);
549 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
552 $relationFrom = " {$relationFrom}
553 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
554 {$relationshipJoin} ";
556 //check for active relationship status only
557 $today = date('Ymd');
558 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
559 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
560 $relationGroupBy = " GROUP BY crel.{$contactA}";
561 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
562 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
564 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
565 while ($allRelContactDAO->fetch()) {
566 //FIX Me: Migrate this to table rather than array
567 // build the array of all related contacts
568 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
570 $allRelContactDAO->free();
574 // make sure the groups stuff is included only if specifically specified
575 // by the fields param (CRM-1969), else we limit the contacts outputted to only
576 // ones that are part of a group
577 if (!empty($returnProperties['groups'])) {
578 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
579 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
580 // total hack for export, CRM-3618
581 $from = str_replace($oldClause,
587 if (!$selectAll && $componentTable) {
588 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
590 elseif ($componentClause) {
592 $where = "WHERE $componentClause";
595 $where .= " AND $componentClause";
599 // CRM-13982 - check if is deleted
600 $excludeTrashed = TRUE;
601 foreach ($params as $value) {
602 if ($value[0] == 'contact_is_deleted') {
603 $excludeTrashed = FALSE;
606 if (empty($where) && $excludeTrashed) {
607 $where = "WHERE contact_a.is_deleted != 1";
609 elseif ($excludeTrashed) {
610 $where .= " AND contact_a.is_deleted != 1";
613 $queryString = "$select $from $where $having";
616 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
617 CRM_Utils_Array
::value('notes', $returnProperties) ||
619 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
621 $groupBy = " GROUP BY contact_a.id";
624 switch ($exportMode) {
625 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
626 $groupBy = 'GROUP BY civicrm_contribution.id';
627 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
628 // especial group by when soft credit columns are included
629 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
633 case CRM_Export_Form_Select
::EVENT_EXPORT
:
634 $groupBy = 'GROUP BY civicrm_participant.id';
637 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
638 $groupBy = " GROUP BY civicrm_membership.id";
642 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
643 $groupBy = " GROUP BY civicrm_activity.id ";
645 $queryString .= $groupBy;
647 // always add contact_a.id to the ORDER clause
648 // so the order is deterministic
650 if (strpos('contact_a.id', $order) === FALSE) {
651 $order .= ", contact_a.id";
655 list($field, $dir) = explode(' ', $order, 2);
656 $field = trim($field);
657 if (!empty($returnProperties[$field])) {
659 $queryString .= " ORDER BY $order";
663 $multipleSelectFields = array('preferred_communication_method' => 1);
665 $addPaymentHeader = FALSE;
667 $paymentDetails = array();
668 if ($paymentFields ||
$selectedPaymentFields) {
670 // get payment related in for event and members
671 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
672 //get all payment headers.
673 // If we haven't selected specific payment fields, load in all the
675 if (!$selectedPaymentFields) {
676 $paymentHeaders = self
::componentPaymentFields();
677 if (!empty($paymentDetails)) {
678 $addPaymentHeader = TRUE;
681 // If we have selected specific payment fields, leave the payment headers
682 // as an empty array; the headers for each selected field will be added
685 $paymentHeaders = array();
687 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
690 $componentDetails = $headerRows = $sqlColumns = array();
693 $rowCount = self
::EXPORT_ROW_COUNT
;
695 // we write to temp table often to avoid using too much memory
700 // for CRM-3157 purposes
701 $i18n = CRM_Core_I18n
::singleton();
702 $outputColumns = array();
703 //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point
704 // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing
705 foreach ($returnProperties as $key => $value) {
706 $outputColumns[$key] = $value;
709 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
710 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
715 while ($dao->fetch()) {
719 //convert the pseudo constants
720 // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
721 // temporary iterationDAO object to get around it.
722 // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
723 // these additional properties are NOT reset when the $dao cycles through the while loop
724 // nor are they overwritten as they are not in the loop
725 // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
726 // relevant property is set.
727 // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
728 // export class before tackling a better architectural fix
729 $iterationDAO = clone $dao;
730 $query->convertToPseudoNames($iterationDAO);
732 //first loop through output columns so that we return what is required, and in same order.
733 $relationshipField = 0;
734 foreach ($outputColumns as $field => $value) {
735 //we should set header only once
738 // Split campaign into 2 fields for id and title
739 if (substr($field, -14) == 'campaign_title') {
740 $headerRows[] = ts('Campaign Title');
742 elseif (substr($field, -11) == 'campaign_id') {
743 $headerRows[] = ts('Campaign ID');
745 elseif (isset($query->_fields
[$field]['title'])) {
746 $headerRows[] = $query->_fields
[$field]['title'];
748 elseif ($field == 'phone_type_id') {
749 $headerRows[] = ts('Phone Type');
751 elseif ($field == 'provider_id') {
752 $headerRows[] = ts('IM Service Provider');
754 elseif (is_array($value) && $field == 'location') {
755 // fix header for location type case
756 foreach ($value as $ltype => $val) {
757 foreach (array_keys($val) as $fld) {
758 $type = explode('-', $fld);
759 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
761 if (!empty($type[1])) {
762 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
763 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
765 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
766 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
769 $headerRows[] = $hdr;
770 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
775 elseif (substr($field, 0, 5) == 'case_') {
776 if ($query->_fields
['case'][$field]['title']) {
777 $headerRows[] = $query->_fields
['case'][$field]['title'];
779 elseif ($query->_fields
['activity'][$field]['title']) {
780 $headerRows[] = $query->_fields
['activity'][$field]['title'];
783 elseif (array_key_exists($field, $contactRelationshipTypes)) {
785 foreach ($value as $relationField => $relationValue) {
786 // below block is same as primary block (duplicate)
787 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
788 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
789 $headerName = $field . '-' . $relationField;
792 if ($relationField == 'current_employer') {
793 $headerName = $field . '-' . 'current_employer';
796 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
800 $headerRows[] = $headerName;
802 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
804 elseif ($relationField == 'phone_type_id') {
805 $headerName = $field . '-' . 'Phone Type';
806 $headerRows[] = $headerName;
807 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
809 elseif ($relationField == 'provider_id') {
810 $headerName = $field . '-' . 'Im Service Provider';
811 $headerRows[] = $headerName;
812 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
814 elseif ($relationField == 'state_province_id') {
815 $headerName = $field . '-' . 'state_province_id';
816 $headerRows[] = $headerName;
817 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
819 elseif (is_array($relationValue) && $relationField == 'location') {
820 // fix header for location type case
821 foreach ($relationValue as $ltype => $val) {
822 foreach (array_keys($val) as $fld) {
823 $type = explode('-', $fld);
825 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
827 if (!empty($type[1])) {
828 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
829 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
831 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
832 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
835 $headerName = $field . '-' . $hdr;
836 $headerRows[] = $headerName;
837 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
843 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
844 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
847 $headerRows[] = $field;
851 self
::sqlColumnDefn($query, $sqlColumns, $field);
855 // add im_provider to $dao object
856 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
857 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
860 //build row values (data)
862 if (property_exists($iterationDAO, $field)) {
863 $fieldValue = $iterationDAO->$field;
864 // to get phone type from phone type id
865 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
866 $fieldValue = $phoneTypes[$fieldValue];
868 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
869 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
871 elseif ($field == 'participant_role_id') {
872 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
873 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
874 $viewRoles = array();
875 foreach (explode($sep, $iterationDAO->$field) as $k => $v) {
876 $viewRoles[] = $participantRoles[$v];
878 $fieldValue = implode(',', $viewRoles);
880 elseif ($field == 'master_id') {
881 $masterAddressId = NULL;
882 if (isset($iterationDAO->master_id
)) {
883 $masterAddressId = $iterationDAO->master_id
;
885 // get display name of contact that address is shared.
886 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id
);
890 if ($field == 'id') {
891 $row[$field] = $iterationDAO->contact_id
;
892 // special case for calculated field
894 elseif ($field == 'source_contact_id') {
895 $row[$field] = $iterationDAO->contact_id
;
897 elseif ($field == 'pledge_balance_amount') {
898 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
899 // special case for calculated field
901 elseif ($field == 'pledge_next_pay_amount') {
902 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
904 elseif (is_array($value) && $field == 'location') {
905 // fix header for location type case
906 foreach ($value as $ltype => $val) {
907 foreach (array_keys($val) as $fld) {
908 $type = explode('-', $fld);
909 $fldValue = "{$ltype}-" . $type[0];
910 // CRM-14076 - fix label to work as the query object expects
911 // FIXME: We should not be using labels as keys!
912 $daoField = CRM_Utils_String
::munge($ltype) . '-' . $type[0];
914 if (!empty($type[1])) {
915 $fldValue .= "-" . $type[1];
916 $daoField .= "-" . $type[1];
919 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
923 $row[$fldValue] = $i18n->crm_translate($iterationDAO->$daoField, array('context' => 'country'));
926 case 'state_province':
927 $row[$fldValue] = $i18n->crm_translate($iterationDAO->$daoField, array('context' => 'province'));
931 $imFieldvalue = $daoField . "-provider_id";
932 $row[$fldValue] = CRM_Utils_Array
::value($iterationDAO->$imFieldvalue, $imProviders);
936 $row[$fldValue] = $iterationDAO->$daoField;
942 elseif (array_key_exists($field, $contactRelationshipTypes)) {
943 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
944 $relationQuery[$field]->convertToPseudoNames($relDAO);
945 foreach ($value as $relationField => $relationValue) {
946 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
947 $fieldValue = $relDAO->$relationField;
948 if ($relationField == 'phone_type_id') {
949 $fieldValue = $phoneTypes[$relationValue];
951 elseif ($relationField == 'provider_id') {
952 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
955 elseif (is_object($relDAO) && in_array($relationField, array(
961 //special case for greeting replacement
962 $fldValue = "{$relationField}_display";
963 $fieldValue = $relDAO->$fldValue;
966 elseif (is_object($relDAO) && $relationField == 'state_province') {
967 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
969 elseif (is_object($relDAO) && $relationField == 'country') {
970 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
975 $field = $field . '_';
977 if (array_key_exists($relationField, $multipleSelectFields)) {
978 $param = array($relationField => $fieldValue);
979 $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
980 CRM_Core_OptionGroup
::lookupValues($param, $names, FALSE);
981 $fieldValue = $param[$relationField];
983 if (is_object($relDAO) && $relationField == 'id') {
984 $row[$field . $relationField] = $relDAO->contact_id
;
986 elseif (is_array($relationValue) && $relationField == 'location') {
987 foreach ($relationValue as $ltype => $val) {
988 foreach (array_keys($val) as $fld) {
989 $type = explode('-', $fld);
990 $fldValue = "{$ltype}-" . $type[0];
991 if (!empty($type[1])) {
992 $fldValue .= "-" . $type[1];
994 // CRM-3157: localise country, region (both have ‘country’ context)
995 // and state_province (‘province’ context)
997 case (!is_object($relDAO)):
998 $row[$field . '_' . $fldValue] = '';
1001 case in_array('country', $type):
1002 case in_array('world_region', $type):
1003 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1004 array('context' => 'country')
1008 case in_array('state_province', $type):
1009 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1010 array('context' => 'province')
1015 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1021 elseif (isset($fieldValue) && $fieldValue != '') {
1022 //check for custom data
1023 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1024 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
1025 $relationQuery[$field]->_options
1029 //normal relationship fields
1030 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1031 switch ($relationField) {
1033 case 'world_region':
1034 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1037 case 'state_province':
1038 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1042 $row[$field . $relationField] = $fieldValue;
1048 // if relation field is empty or null
1049 $row[$field . $relationField] = '';
1053 elseif (isset($fieldValue) &&
1056 //check for custom data
1057 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1058 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
1060 elseif (array_key_exists($field, $multipleSelectFields)) {
1061 //option group fixes
1062 $paramsNew = array($field => $fieldValue);
1063 if ($field == 'test_tutoring') {
1064 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
1065 // for readers group
1067 elseif (substr($field, 0, 4) == 'cmr_') {
1068 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
1071 $name = array($field => array('newName' => $field, 'groupName' => $field));
1073 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
1074 $row[$field] = $paramsNew[$field];
1077 elseif (in_array($field, array(
1082 //special case for greeting replacement
1083 $fldValue = "{$field}_display";
1084 $row[$field] = $iterationDAO->$fldValue;
1087 //normal fields with a touch of CRM-3157
1090 case 'world_region':
1091 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1094 case 'state_province':
1095 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1099 case 'preferred_communication_method':
1100 case 'preferred_mail_format':
1101 case 'communication_style':
1102 $row[$field] = $i18n->crm_translate($fieldValue);
1106 $row[$field] = $fieldValue;
1111 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1112 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1113 $payFieldMapper = array(
1114 'componentPaymentField_total_amount' => 'total_amount',
1115 'componentPaymentField_contribution_status' => 'contribution_status',
1116 'componentPaymentField_payment_instrument' => 'pay_instru',
1117 'componentPaymentField_transaction_id' => 'trxn_id',
1118 'componentPaymentField_received_date' => 'receive_date',
1120 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1123 // if field is empty or null
1128 // add payment headers if required
1129 if ($addPaymentHeader && $paymentFields) {
1130 $headerRows = array_merge($headerRows, $paymentHeaders);
1131 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1132 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1137 $exportTempTable = self
::createTempTable($sqlColumns);
1140 //build header only once
1143 // If specific payment fields have been selected for export, payment
1144 // data will already be in $row. Otherwise, add payment related
1145 // information, if appropriate.
1146 if ($addPaymentHeader) {
1147 if (!$selectedPaymentFields) {
1148 if ($paymentFields) {
1149 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1150 if (!is_array($paymentData) ||
empty($paymentData)) {
1151 $paymentData = $nullContributionDetails;
1153 $row = array_merge($row, $paymentData);
1155 elseif (!empty($paymentDetails)) {
1156 $row = array_merge($row, $nullContributionDetails);
1160 //remove organization name for individuals if it is set for current employer
1161 if (!empty($row['contact_type']) &&
1162 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1164 $row['organization_name'] = '';
1167 // add component info
1168 // write the row to a file
1169 $componentDetails[] = $row;
1171 // output every $tempRowCount rows
1172 if ($count %
$tempRowCount == 0) {
1173 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1174 $componentDetails = array();
1178 $offset +
= $rowCount;
1181 if ($exportTempTable) {
1182 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1184 // do merge same address and merge same household processing
1185 if ($mergeSameAddress) {
1186 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1189 // merge the records if they have corresponding households
1190 if ($mergeSameHousehold) {
1191 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1192 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1195 // fix the headers for rows with relationship type
1196 if (!empty($relName)) {
1197 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1200 // if postalMailing option is checked, exclude contacts who are deceased, have
1201 // "Do not mail" privacy setting, or have no street address
1202 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1203 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1205 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1209 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1211 // now write the CSV file
1212 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1214 // delete the export temp table and component table
1215 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1216 CRM_Core_DAO
::executeQuery($sql);
1218 CRM_Utils_System
::civiExit();
1221 CRM_Core_Error
::fatal(ts('No records to export'));
1226 * Name of the export file based on mode.
1228 * @param string $output
1236 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1238 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1239 return ts('CiviCRM Contact Search');
1241 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1242 return ts('CiviCRM Contribution Search');
1244 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1245 return ts('CiviCRM Member Search');
1247 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1248 return ts('CiviCRM Participant Search');
1250 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1251 return ts('CiviCRM Pledge Search');
1253 case CRM_Export_Form_Select
::CASE_EXPORT
:
1254 return ts('CiviCRM Case Search');
1256 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1257 return ts('CiviCRM Grant Search');
1259 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1260 return ts('CiviCRM Activity Search');
1265 * Handle import error file creation.
1267 public static function invoke() {
1268 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1269 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1270 if (empty($parserName) ||
empty($type)) {
1274 // clean and ensure parserName is a valid string
1275 $parserName = CRM_Utils_String
::munge($parserName);
1276 $parserClass = explode('_', $parserName);
1278 // make sure parserClass is in the CRM namespace and
1279 // at least 3 levels deep
1280 if ($parserClass[0] == 'CRM' &&
1281 count($parserClass) >= 3
1283 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
1284 // ensure the functions exists
1285 if (method_exists($parserName, 'errorFileName') &&
1286 method_exists($parserName, 'saveFileName')
1288 $errorFileName = $parserName::errorFileName($type);
1289 $saveFileName = $parserName::saveFileName($type);
1290 if (!empty($errorFileName) && !empty($saveFileName)) {
1291 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
1292 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
1293 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
1294 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1295 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1297 readfile($errorFileName);
1301 CRM_Utils_System
::civiExit();
1305 * @param $customSearchClass
1306 * @param $formValues
1309 public static function exportCustom($customSearchClass, $formValues, $order) {
1310 $ext = CRM_Extension_System
::singleton()->getMapper();
1311 if (!$ext->isExtensionClass($customSearchClass)) {
1312 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1315 require_once $ext->classToPath($customSearchClass);
1317 $search = new $customSearchClass($formValues);
1319 $includeContactIDs = FALSE;
1320 if ($formValues['radio_ts'] == 'ts_sel') {
1321 $includeContactIDs = TRUE;
1324 $sql = $search->all(0, 0, $order, $includeContactIDs);
1326 $columns = $search->columns();
1328 $header = array_keys($columns);
1329 $fields = array_values($columns);
1332 $dao = CRM_Core_DAO
::executeQuery($sql);
1334 if (method_exists($search, 'alterRow')) {
1337 while ($dao->fetch()) {
1340 foreach ($fields as $field) {
1341 $row[$field] = $dao->$field;
1344 $search->alterRow($row);
1349 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1350 CRM_Utils_System
::civiExit();
1355 * @param $sqlColumns
1358 public static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1359 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1363 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1364 if ($fieldName == 'id') {
1365 $fieldName = 'civicrm_primary_id';
1368 // early exit for master_id, CRM-12100
1369 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1370 // also for current_employer, CRM-16939
1371 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
1372 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1376 if (substr($fieldName, -11) == 'campaign_id') {
1378 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1382 $lookUp = array('prefix_id', 'suffix_id');
1383 // set the sql columns
1384 if (isset($query->_fields
[$field]['type'])) {
1385 switch ($query->_fields
[$field]['type']) {
1386 case CRM_Utils_Type
::T_INT
:
1387 case CRM_Utils_Type
::T_BOOLEAN
:
1388 if (in_array($field, $lookUp)) {
1389 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1392 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1396 case CRM_Utils_Type
::T_STRING
:
1397 if (isset($query->_fields
[$field]['maxlength'])) {
1398 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1401 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1405 case CRM_Utils_Type
::T_TEXT
:
1406 case CRM_Utils_Type
::T_LONGTEXT
:
1407 case CRM_Utils_Type
::T_BLOB
:
1408 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1409 $sqlColumns[$fieldName] = "$fieldName longtext";
1412 case CRM_Utils_Type
::T_FLOAT
:
1413 case CRM_Utils_Type
::T_ENUM
:
1414 case CRM_Utils_Type
::T_DATE
:
1415 case CRM_Utils_Type
::T_TIME
:
1416 case CRM_Utils_Type
::T_TIMESTAMP
:
1417 case CRM_Utils_Type
::T_MONEY
:
1418 case CRM_Utils_Type
::T_EMAIL
:
1419 case CRM_Utils_Type
::T_URL
:
1420 case CRM_Utils_Type
::T_CCNUM
:
1422 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1427 if (substr($fieldName, -3, 3) == '_id') {
1428 // for trxn_id and its variants use a longer buffer
1429 // to accommodate different systems - CRM-13739
1430 static $notRealIDFields = NULL;
1431 if ($notRealIDFields == NULL) {
1432 $notRealIDFields = array('trxn_id', 'componentpaymentfield_transaction_id');
1435 if (in_array($fieldName, $notRealIDFields)) {
1436 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1439 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1442 elseif (substr($fieldName, -5, 5) == '_note') {
1443 $sqlColumns[$fieldName] = "$fieldName text";
1446 $changeFields = array(
1452 if (in_array($fieldName, $changeFields)) {
1453 $sqlColumns[$fieldName] = "$fieldName text";
1456 // set the sql columns for custom data
1457 if (isset($query->_fields
[$field]['data_type'])) {
1459 switch ($query->_fields
[$field]['data_type']) {
1461 $length = empty($query->_fields
[$field]['text_length']) ?
255 : $query->_fields
[$field]['text_length'];
1462 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1466 case 'StateProvince':
1468 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1472 $sqlColumns[$fieldName] = "$fieldName text";
1476 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1481 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1489 * @param string $tableName
1491 * @param $sqlColumns
1493 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1494 if (empty($details)) {
1503 $id = CRM_Core_DAO
::singleValueQuery($sql);
1508 $sqlClause = array();
1510 foreach ($details as $dontCare => $row) {
1512 $valueString = array($id);
1513 foreach ($row as $dontCare => $value) {
1514 if (empty($value)) {
1515 $valueString[] = "''";
1518 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1521 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1524 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1526 $sqlValueString = implode(",\n", $sqlClause);
1529 INSERT INTO $tableName $sqlColumnString
1530 VALUES $sqlValueString
1533 CRM_Core_DAO
::executeQuery($sql);
1537 * @param $sqlColumns
1541 public static function createTempTable(&$sqlColumns) {
1542 //creating a temporary table for the search result that need be exported
1543 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1545 // also create the sql table
1546 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1547 CRM_Core_DAO
::executeQuery($sql);
1550 CREATE TABLE {$exportTempTable} (
1551 id int unsigned NOT NULL AUTO_INCREMENT,
1553 $sql .= implode(",\n", array_values($sqlColumns));
1558 // add indexes for street_address and household_name if present
1559 $addIndices = array(
1562 'civicrm_primary_id',
1565 foreach ($addIndices as $index) {
1566 if (isset($sqlColumns[$index])) {
1568 INDEX index_{$index}( $index )
1574 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1577 CRM_Core_DAO
::executeQuery($sql);
1578 return $exportTempTable;
1582 * @param string $tableName
1583 * @param $headerRows
1584 * @param $sqlColumns
1585 * @param array $exportParams
1587 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1588 // check if any records are present based on if they have used shared address feature,
1589 // and not based on if city / state .. matches.
1591 SELECT r1.id as copy_id,
1592 r1.civicrm_primary_id as copy_contact_id,
1593 r1.addressee as copy_addressee,
1594 r1.addressee_id as copy_addressee_id,
1595 r1.postal_greeting as copy_postal_greeting,
1596 r1.postal_greeting_id as copy_postal_greeting_id,
1598 r2.civicrm_primary_id as master_contact_id,
1599 r2.postal_greeting as master_postal_greeting,
1600 r2.postal_greeting_id as master_postal_greeting_id,
1601 r2.addressee as master_addressee,
1602 r2.addressee_id as master_addressee_id
1604 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1605 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1607 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1609 // find all the records that have the same street address BUT not in a household
1610 // require match on city and state as well
1612 SELECT r1.id as master_id,
1613 r1.civicrm_primary_id as master_contact_id,
1614 r1.postal_greeting as master_postal_greeting,
1615 r1.postal_greeting_id as master_postal_greeting_id,
1616 r1.addressee as master_addressee,
1617 r1.addressee_id as master_addressee_id,
1619 r2.civicrm_primary_id as copy_contact_id,
1620 r2.postal_greeting as copy_postal_greeting,
1621 r2.postal_greeting_id as copy_postal_greeting_id,
1622 r2.addressee as copy_addressee,
1623 r2.addressee_id as copy_addressee_id
1625 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1626 r1.city = r2.city AND
1627 r1.state_province_id = r2.state_province_id )
1628 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1629 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1630 AND ( r1.street_address != '' )
1634 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1636 // unset ids from $merge already present in $linkedMerge
1637 foreach ($linkedMerge as $masterID => $values) {
1638 $keys = array($masterID);
1639 $keys = array_merge($keys, array_keys($values['copy']));
1640 foreach ($merge as $mid => $vals) {
1641 if (in_array($mid, $keys)) {
1642 unset($merge[$mid]);
1645 foreach ($values['copy'] as $copyId) {
1646 if (in_array($copyId, $keys)) {
1647 unset($merge[$mid]['copy'][$copyId]);
1653 $merge = $merge +
$linkedMerge;
1655 foreach ($merge as $masterID => $values) {
1658 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1662 1 => array($values['addressee'], 'String'),
1663 2 => array($values['postalGreeting'], 'String'),
1664 3 => array($values['emailGreeting'], 'String'),
1665 4 => array($masterID, 'Integer'),
1667 CRM_Core_DAO
::executeQuery($sql, $params);
1669 // delete all copies
1670 $deleteIDs = array_keys($values['copy']);
1671 $deleteIDString = implode(',', $deleteIDs);
1673 DELETE FROM $tableName
1674 WHERE id IN ( $deleteIDString )
1676 CRM_Core_DAO
::executeQuery($sql);
1679 // unset temporary columns that were added for postal mailing format
1680 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1681 $unsetKeys = array_keys($sqlColumns);
1682 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1683 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1684 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1691 * @param int $contactId
1692 * @param array $exportParams
1696 public static function _replaceMergeTokens($contactId, $exportParams) {
1697 $greetings = array();
1700 $greetingFields = array(
1704 foreach ($greetingFields as $greeting) {
1705 if (!empty($exportParams[$greeting])) {
1706 $greetingLabel = $exportParams[$greeting];
1707 if (empty($contact)) {
1712 $contact = civicrm_api('contact', 'get', $values);
1714 if (!empty($contact['is_error'])) {
1717 $contact = $contact['values'][$contact['id']];
1720 $tokens = array('contact' => $greetingLabel);
1721 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1728 * The function unsets static part of the string, if token is the dynamic part.
1729 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1730 * i.e 'Hello Alan' => converted to => 'Alan'
1732 public static function _trimNonTokens(
1733 &$parsedString, $defaultGreeting,
1734 $addressMergeGreetings, $greetingType = 'postal_greeting'
1736 if (!empty($addressMergeGreetings[$greetingType])) {
1737 $greetingLabel = $addressMergeGreetings[$greetingType];
1739 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1741 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1742 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1743 foreach ($stringsToBeReplaced as $key => $string) {
1744 // to keep one space
1745 $stringsToBeReplaced[$key] = ltrim($string);
1747 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1749 return $parsedString;
1754 * @param array $exportParams
1755 * @param bool $sharedAddress
1759 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1760 static $contactGreetingTokens = array();
1762 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1763 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1765 $merge = $parents = array();
1766 $dao = CRM_Core_DAO
::executeQuery($sql);
1768 while ($dao->fetch()) {
1769 $masterID = $dao->master_id
;
1770 $copyID = $dao->copy_id
;
1771 $masterPostalGreeting = $dao->master_postal_greeting
;
1772 $masterAddressee = $dao->master_addressee
;
1773 $copyAddressee = $dao->copy_addressee
;
1775 if (!$sharedAddress) {
1776 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1777 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1779 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1780 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1782 $masterAddressee = CRM_Utils_Array
::value('addressee',
1783 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1786 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1787 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1789 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1790 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1792 $copyAddressee = CRM_Utils_Array
::value('addressee',
1793 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1797 if (!isset($merge[$masterID])) {
1798 // check if this is an intermediate child
1799 // this happens if there are 3 or more matches a,b, c
1800 // the above query will return a, b / a, c / b, c
1801 // we might be doing a bit more work, but for now its ok, unless someone
1802 // knows how to fix the query above
1803 if (isset($parents[$masterID])) {
1804 $masterID = $parents[$masterID];
1807 $merge[$masterID] = array(
1808 'addressee' => $masterAddressee,
1810 'postalGreeting' => $masterPostalGreeting,
1812 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1815 $parents[$copyID] = $masterID;
1817 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1819 if (!empty($exportParams['postal_greeting_other']) &&
1820 count($merge[$masterID]['copy']) >= 1
1822 // use static greetings specified if no of contacts > 2
1823 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1825 elseif ($copyPostalGreeting) {
1826 self
::_trimNonTokens($copyPostalGreeting,
1827 $postalOptions[$dao->copy_postal_greeting_id
],
1830 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1831 // if there happens to be a duplicate, remove it
1832 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1835 if (!empty($exportParams['addressee_other']) &&
1836 count($merge[$masterID]['copy']) >= 1
1838 // use static greetings specified if no of contacts > 2
1839 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1841 elseif ($copyAddressee) {
1842 self
::_trimNonTokens($copyAddressee,
1843 $addresseeOptions[$dao->copy_addressee_id
],
1844 $exportParams, 'addressee'
1846 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1849 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1856 * Merge household record into the individual record
1859 * @param string $exportTempTable
1860 * Temporary temp table that stores the records.
1861 * @param array $headerRows
1862 * Array of headers for the export file.
1863 * @param array $sqlColumns
1864 * Array of names of the table columns of the temp table.
1865 * @param string $prefix
1866 * Name of the relationship type that is prefixed to the table columns.
1868 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1869 $prefixColumn = $prefix . '_';
1870 $allKeys = array_keys($sqlColumns);
1871 $replaced = array();
1872 $headerRows = array_values($headerRows);
1874 // name map of the non standard fields in header rows & sql columns
1875 $mappingFields = array(
1876 'civicrm_primary_id' => 'id',
1877 'contact_source' => 'source',
1878 'current_employer_id' => 'employer_id',
1879 'contact_is_deleted' => 'is_deleted',
1880 'name' => 'address_name',
1881 'provider_id' => 'im_service_provider',
1882 'phone_type_id' => 'phone_type',
1885 //figure out which columns are to be replaced by which ones
1886 foreach ($sqlColumns as $columnNames => $dontCare) {
1887 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1888 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1891 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1893 if (!empty($sqlColumns[$householdColName])) {
1894 $replaced[$columnNames] = $householdColName;
1898 $query = "UPDATE $exportTempTable SET ";
1901 foreach ($replaced as $from => $to) {
1902 $clause[] = "$from = $to ";
1903 unset($sqlColumns[$to]);
1904 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1905 unset($headerRows[$key]);
1908 $query .= implode(",\n", $clause);
1909 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1911 CRM_Core_DAO
::executeQuery($query);
1913 //drop the table columns that store redundant household info
1914 $dropQuery = "ALTER TABLE $exportTempTable ";
1915 foreach ($replaced as $householdColumns) {
1916 $dropClause[] = " DROP $householdColumns ";
1918 $dropQuery .= implode(",\n", $dropClause);
1920 CRM_Core_DAO
::executeQuery($dropQuery);
1922 // also drop the temp table if exists
1923 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1924 CRM_Core_DAO
::executeQuery($sql);
1926 // clean up duplicate records
1928 CREATE TABLE {$exportTempTable}_temp SELECT *
1929 FROM {$exportTempTable}
1930 GROUP BY civicrm_primary_id ";
1932 CRM_Core_DAO
::executeQuery($query);
1934 $query = "DROP TABLE $exportTempTable";
1935 CRM_Core_DAO
::executeQuery($query);
1937 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1938 CRM_Core_DAO
::executeQuery($query);
1942 * @param $exportTempTable
1943 * @param $headerRows
1944 * @param $sqlColumns
1945 * @param $exportMode
1946 * @param null $saveFile
1947 * @param string $batchItems
1949 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1950 $writeHeader = TRUE;
1952 $limit = self
::EXPORT_ROW_COUNT
;
1954 $query = "SELECT * FROM $exportTempTable";
1957 $limitQuery = $query . "
1958 LIMIT $offset, $limit
1960 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1966 $componentDetails = array();
1967 while ($dao->fetch()) {
1970 foreach ($sqlColumns as $column => $dontCare) {
1971 $row[$column] = $dao->$column;
1973 $componentDetails[] = $row;
1975 if ($exportMode == 'financial') {
1976 $getExportFileName = 'CiviCRM Contribution Search';
1979 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1981 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1988 if ($saveFile && !empty($csvRows)) {
1989 $batchItems .= $csvRows;
1992 $writeHeader = FALSE;
1998 * Manipulate header rows for relationship fields.
2000 * @param $headerRows
2001 * @param $contactRelationshipTypes
2003 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
2004 foreach ($headerRows as & $header) {
2005 $split = explode('-', $header);
2006 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
2007 $split[0] = $relationTypeName;
2008 $header = implode('-', $split);
2014 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
2015 * or have no street address
2016 * @param $exportTempTable
2017 * @param $headerRows
2018 * @param $sqlColumns
2019 * @param $exportParams
2021 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
2022 $whereClause = array();
2024 if (array_key_exists('is_deceased', $sqlColumns)) {
2025 $whereClause[] = 'is_deceased = 1';
2028 if (array_key_exists('do_not_mail', $sqlColumns)) {
2029 $whereClause[] = 'do_not_mail = 1';
2032 if (array_key_exists('street_address', $sqlColumns)) {
2033 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
2035 // check for supplemental_address_1
2036 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
2037 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
2038 'address_options', TRUE, NULL, TRUE
2040 if (!empty($addressOptions['supplemental_address_1'])) {
2041 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
2042 // enclose it again, since we are doing an AND in between a set of ORs
2043 $addressWhereClause = "( $addressWhereClause )";
2047 $whereClause[] = $addressWhereClause;
2050 if (!empty($whereClause)) {
2051 $whereClause = implode(' OR ', $whereClause);
2054 FROM $exportTempTable
2055 WHERE {$whereClause}";
2056 CRM_Core_DAO
::singleValueQuery($query);
2059 // unset temporary columns that were added for postal mailing format
2060 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
2061 $unsetKeys = array_keys($sqlColumns);
2062 foreach ($unsetKeys as $headerKey => $sqlColKey) {
2063 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
2064 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
2071 * Build componentPayment fields.
2073 public static function componentPaymentFields() {
2074 static $componentPaymentFields;
2075 if (!isset($componentPaymentFields)) {
2076 $componentPaymentFields = array(
2077 'componentPaymentField_total_amount' => ts('Total Amount'),
2078 'componentPaymentField_contribution_status' => ts('Contribution Status'),
2079 'componentPaymentField_received_date' => ts('Date Received'),
2080 'componentPaymentField_payment_instrument' => ts('Payment Method'),
2081 'componentPaymentField_transaction_id' => ts('Transaction ID'),
2084 return $componentPaymentFields;