3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * This class contains the funtions for Component export
40 class CRM_Export_BAO_Export
{
41 // increase this number a lot to avoid making too many queries
42 // LIMIT is not much faster than a no LIMIT query
44 const EXPORT_ROW_COUNT
= 10000;
47 * Get the list the export fields
49 * @param int $selectAll user preference while export
50 * @param array $ids contact ids
51 * @param array $params associated array of fields
52 * @param string $order order by clause
53 * @param array $fields associated array of fields
54 * @param array $moreReturnProperties additional return fields
55 * @param int $exportMode export mode
56 * @param string $componentClause component clause
57 * @param string $componentTable component table
58 * @param bool $mergeSameAddress merge records if they have same address
59 * @param bool $mergeSameHousehold merge records if they belong to the same household
61 * @param array $exportParams
62 * @param string $queryOperator
66 static function exportComponents($selectAll,
71 $moreReturnProperties = NULL,
72 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
73 $componentClause = NULL,
74 $componentTable = NULL,
75 $mergeSameAddress = FALSE,
76 $mergeSameHousehold = FALSE,
77 $exportParams = array(),
78 $queryOperator = 'AND'
80 $headerRows = $returnProperties = array();
81 $primary = $paymentFields = $selectedPaymentFields = FALSE;
82 $origFields = $fields;
83 $relationField = NULL;
85 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
86 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
87 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
96 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
98 switch ($exportMode) {
99 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
100 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
103 case CRM_Export_Form_Select
::EVENT_EXPORT
:
104 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
107 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
108 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
111 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
112 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
115 case CRM_Export_Form_Select
::CASE_EXPORT
:
116 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
119 case CRM_Export_Form_Select
::GRANT_EXPORT
:
120 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
123 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
124 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
128 //construct return properties
129 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
130 $locationTypeFields = array(
132 'supplemental_address_1',
133 'supplemental_address_2',
136 'postal_code_suffix',
146 foreach ($fields as $key => $value) {
147 $phoneTypeId = $imProviderId = NULL;
148 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
152 // get phoneType id and IM service provider id seperately
153 if ($fieldName == 'phone') {
154 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
156 elseif ($fieldName == 'im') {
157 $imProviderId = CRM_Utils_Array
::value(3, $value);
160 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
161 if (!empty($value[2])) {
162 $relationField = CRM_Utils_Array
::value(2, $value);
163 if (trim(CRM_Utils_Array
::value(3, $value))) {
164 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
167 $relLocTypeId = 'Primary';
170 if ($relationField == 'phone') {
171 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
173 elseif ($relationField == 'im') {
174 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
177 elseif (!empty($value[4])) {
178 $relationField = CRM_Utils_Array
::value(4, $value);
179 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
180 if ($relationField == 'phone') {
181 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
183 elseif ($relationField == 'im') {
184 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
189 $contactType = CRM_Utils_Array
::value(0, $value);
190 $locTypeId = CRM_Utils_Array
::value(2, $value);
192 if ($relationField) {
193 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
194 if ($relPhoneTypeId) {
195 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
197 elseif ($relIMProviderId) {
198 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
201 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
203 $relPhoneTypeId = $relIMProviderId = NULL;
206 $returnProperties[$relationshipTypes][$relationField] = 1;
209 elseif (is_numeric($locTypeId)) {
211 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
213 elseif ($imProviderId) {
214 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
217 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
221 //hack to fix component fields
222 //revert mix of event_id and title
223 if ($fieldName == 'event_id') {
224 $returnProperties['event_id'] = 1;
227 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
228 array_key_exists( $fieldName, self
::componentPaymentFields())
230 $selectedPaymentFields = true;
231 $paymentTableId = 'participant_id';
232 $returnProperties[$fieldName] = 1;
235 $returnProperties[$fieldName] = 1;
240 // hack to add default returnproperty based on export mode
241 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
242 $returnProperties['contribution_id'] = 1;
244 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
245 $returnProperties['participant_id'] = 1;
246 if (!empty($returnProperties['participant_role'])) {
247 unset($returnProperties['participant_role']);
248 $returnProperties['participant_role_id'] = 1;
251 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
252 $returnProperties['membership_id'] = 1;
254 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
255 $returnProperties['pledge_id'] = 1;
257 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
258 $returnProperties['case_id'] = 1;
260 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
261 $returnProperties['grant_id'] = 1;
263 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
264 $returnProperties['activity_id'] = 1;
269 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
270 foreach ($fields as $key => $var) {
271 if ($key && (substr($key, 0, 6) != 'custom')) {
273 $returnProperties[$key] = 1;
278 $returnProperties['location_type'] = 1;
279 $returnProperties['im_provider'] = 1;
280 $returnProperties['phone_type_id'] = 1;
281 $returnProperties['provider_id'] = 1;
282 $returnProperties['current_employer'] = 1;
285 $extraReturnProperties = array();
286 $paymentFields = FALSE;
288 switch ($queryMode) {
289 case CRM_Contact_BAO_Query
::MODE_EVENT
:
290 $paymentFields = TRUE;
291 $paymentTableId = 'participant_id';
294 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
295 $paymentFields = TRUE;
296 $paymentTableId = 'membership_id';
299 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
300 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
301 $paymentFields = TRUE;
302 $paymentTableId = 'pledge_payment_id';
305 case CRM_Contact_BAO_Query
::MODE_CASE
:
306 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
310 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
311 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
312 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
313 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
314 $componentReturnProperties =
316 $componentReturnProperties,
317 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
319 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
321 if (!empty($extraReturnProperties)) {
322 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
325 // unset non exportable fields for components
326 $nonExpoFields = array(
327 'groups', 'tags', 'notes', 'contribution_status_id',
328 'pledge_status_id', 'pledge_payment_status_id',
330 foreach ($nonExpoFields as $value) {
331 unset($returnProperties[$value]);
336 if ($mergeSameAddress) {
337 //make sure the addressee fields are selected
338 //while using merge same address feature
339 $returnProperties['addressee'] = 1;
340 $returnProperties['postal_greeting'] = 1;
341 $returnProperties['email_greeting'] = 1;
342 $returnProperties['street_name'] = 1;
343 $returnProperties['household_name'] = 1;
344 $returnProperties['street_address'] = 1;
345 $returnProperties['city'] = 1;
346 $returnProperties['state_province'] = 1;
348 // some columns are required for assistance incase they are not already present
349 $exportParams['merge_same_address']['temp_columns'] = array();
350 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
351 foreach ($tempColumns as $column) {
352 if (!array_key_exists($column, $returnProperties)) {
353 $returnProperties[$column] = 1;
354 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
355 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
360 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
361 // If an Additional Group is selected, then all contacts in that group are
362 // added to the export set (filtering out duplicates).
364 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";
365 CRM_Core_DAO
::executeQuery($query);
368 if ($moreReturnProperties) {
370 if (!empty($moreReturnProperties['group'])) {
371 unset($moreReturnProperties['group']);
372 $moreReturnProperties['groups'] = 1;
374 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
377 $exportParams['postal_mailing_export']['temp_columns'] = array();
378 if ($exportParams['exportOption'] == 2 &&
379 isset($exportParams['postal_mailing_export']) &&
380 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
382 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
383 foreach ($postalColumns as $column) {
384 if (!array_key_exists($column, $returnProperties)) {
385 $returnProperties[$column] = 1;
386 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
391 // rectify params to what proximity search expects if there is a value for prox_distance
393 if (!empty($params)) {
394 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
397 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
398 FALSE, FALSE, $queryMode,
399 FALSE, TRUE, TRUE, NULL, $queryOperator
404 $query->_sort
= $order;
405 list($select, $from, $where, $having) = $query->query();
407 if ($mergeSameHousehold == 1) {
408 if (!$returnProperties['id']) {
409 $returnProperties['id'] = 1;
412 //also merge Head of Household
413 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
414 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
416 foreach ($returnProperties as $key => $value) {
417 if (!array_key_exists($key, $contactRelationshipTypes)) {
418 $returnProperties[$relationKeyMOH][$key] = $value;
419 $returnProperties[$relationKeyHOH][$key] = $value;
423 unset($returnProperties[$relationKeyMOH]['location_type']);
424 unset($returnProperties[$relationKeyMOH]['im_provider']);
425 unset($returnProperties[$relationKeyHOH]['location_type']);
426 unset($returnProperties[$relationKeyHOH]['im_provider']);
429 $allRelContactArray = $relationQuery = array();
431 foreach ($contactRelationshipTypes as $rel => $dnt) {
432 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
433 $allRelContactArray[$rel] = array();
434 // build Query for each relationship
435 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
436 NULL, FALSE, FALSE, $queryMode
438 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
440 list($id, $direction) = explode('_', $rel, 2);
441 // identify the relationship direction
442 $contactA = 'contact_id_a';
443 $contactB = 'contact_id_b';
444 if ($direction == 'b_a') {
445 $contactA = 'contact_id_b';
446 $contactB = 'contact_id_a';
448 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
451 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
452 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
453 $query = "SELECT contact_id FROM civicrm_activity_contact
454 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
455 record_type_id = {$sourceID}";
456 $dao = CRM_Core_DAO
::executeQuery($query);
457 while ($dao->fetch()) {
458 $relIDs[] = $dao->contact_id
;
462 switch ($exportMode) {
463 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
464 $component = 'civicrm_contribution';
467 case CRM_Export_Form_Select
::EVENT_EXPORT
:
468 $component = 'civicrm_participant';
471 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
472 $component = 'civicrm_membership';
475 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
476 $component = 'civicrm_pledge';
479 case CRM_Export_Form_Select
::GRANT_EXPORT
:
480 $component = 'civicrm_grant';
484 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
485 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
488 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
492 $relationshipJoin = $relationshipClause = '';
493 if (!$selectAll && $componentTable) {
494 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
496 elseif (!empty($relIDs)) {
497 $relID = implode(',', $relIDs);
498 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
501 $relationFrom = " {$relationFrom}
502 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
503 {$relationshipJoin} ";
505 //check for active relationship status only
506 $today = date('Ymd');
507 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
508 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
509 $relationGroupBy = " GROUP BY crel.{$contactA}";
510 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
511 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
513 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
514 while ($allRelContactDAO->fetch()) {
515 //FIX Me: Migrate this to table rather than array
516 // build the array of all related contacts
517 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
519 $allRelContactDAO->free();
523 // make sure the groups stuff is included only if specifically specified
524 // by the fields param (CRM-1969), else we limit the contacts outputted to only
525 // ones that are part of a group
526 if (!empty($returnProperties['groups'])) {
527 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
528 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
529 // total hack for export, CRM-3618
530 $from = str_replace($oldClause,
536 if (!$selectAll && $componentTable) {
537 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
539 elseif ($componentClause) {
541 $where = "WHERE $componentClause";
544 $where .= " AND $componentClause";
548 // CRM-13982 - check if is deleted
549 $excludeTrashed = TRUE;
550 foreach ($params as $value) {
551 if ($value[0] == 'contact_is_deleted') {
552 $excludeTrashed = FALSE;
555 if (empty($where) && $excludeTrashed) {
556 $where = "WHERE contact_a.is_deleted != 1";
558 elseif ($excludeTrashed) {
559 $where .= " AND contact_a.is_deleted != 1";
562 $queryString = "$select $from $where $having";
565 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
566 CRM_Utils_Array
::value('notes', $returnProperties) ||
568 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
570 $groupBy = " GROUP BY contact_a.id";
573 switch ($exportMode) {
574 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
575 $groupBy = 'GROUP BY civicrm_contribution.id';
576 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
577 // especial group by when soft credit columns are included
578 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
582 case CRM_Export_Form_Select
::EVENT_EXPORT
:
583 $groupBy = 'GROUP BY civicrm_participant.id';
586 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
587 $groupBy = " GROUP BY civicrm_membership.id";
591 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
592 $groupBy = " GROUP BY civicrm_activity.id ";
594 $queryString .= $groupBy;
596 // always add contact_a.id to the ORDER clause
597 // so the order is deterministic
599 if (strpos('contact_a.id', $order) === FALSE) {
600 $order .= ", contact_a.id";
604 list($field, $dir) = explode(' ', $order, 2);
605 $field = trim($field);
606 if (!empty($returnProperties[$field])) {
608 $queryString .= " ORDER BY $order";
612 $multipleSelectFields = array('preferred_communication_method' => 1);
614 $addPaymentHeader = FALSE;
616 $paymentDetails = array();
617 if ($paymentFields ||
$selectedPaymentFields) {
619 // get payment related in for event and members
620 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
621 //get all payment headers.
622 // If we haven't selected specific payment fields, load in all the
624 if (!$selectedPaymentFields) {
625 $paymentHeaders = self
::componentPaymentFields();
626 if (!empty($paymentDetails)) {
627 $addPaymentHeader = TRUE;
630 // If we have selected specific payment fields, leave the payment headers
631 // as an empty array; the headers for each selected field will be added
634 $paymentHeaders = array();
636 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
639 $componentDetails = $headerRows = $sqlColumns = array();
642 $rowCount = self
::EXPORT_ROW_COUNT
;
644 // we write to temp table often to avoid using too much memory
649 // for CRM-3157 purposes
650 $i18n = CRM_Core_I18n
::singleton();
651 $outputColumns = array();
652 //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point
653 // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing
654 foreach ($returnProperties as $key => $value) {
655 $outputColumns[$key] = $value;
656 if (substr($key, -11) == 'campaign_id') {
657 // the field $dao->x_campaign_id_id holds the id whereas the field $dao->campaign_id
658 // we want to insert it directly after campaign id
659 $outputColumns[$key . '_id'] = 1;
663 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
664 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
669 while ($dao->fetch()) {
673 //convert the pseudo constants
674 // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
675 // temporary iterationDAO object to get around it.
676 // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
677 // these additional properties are NOT reset when the $dao cycles through the while loop
678 // nor are they overwritten as they are not in the loop
679 // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
680 // relevant property is set.
681 // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
682 // export class before tackling a better architectural fix
683 $iterationDAO = clone $dao;
684 $query->convertToPseudoNames($iterationDAO);
686 //first loop through output columns so that we return what is required, and in same order.
687 $relationshipField = 0;
688 foreach ($outputColumns as $field => $value) {
689 //we should set header only once
692 // Split campaign into 2 fields for id and title
693 if (substr($field, -11) == 'campaign_id') {
694 $headerRows[] = ts('Campaign Title');
696 elseif (substr($field, -14) == 'campaign_id_id') {
697 $headerRows[] = ts('Campaign ID');
699 elseif (isset($query->_fields
[$field]['title'])) {
700 $headerRows[] = $query->_fields
[$field]['title'];
702 elseif ($field == 'phone_type_id') {
703 $headerRows[] = ts('Phone Type');
705 elseif ($field == 'provider_id') {
706 $headerRows[] = ts('IM Service Provider');
708 elseif (is_array($value) && $field == 'location') {
709 // fix header for location type case
710 foreach ($value as $ltype => $val) {
711 foreach (array_keys($val) as $fld) {
712 $type = explode('-', $fld);
713 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
715 if (!empty($type[1])) {
716 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
717 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
719 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
720 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
723 $headerRows[] = $hdr;
724 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
729 elseif (substr($field, 0, 5) == 'case_') {
730 if ($query->_fields
['case'][$field]['title']) {
731 $headerRows[] = $query->_fields
['case'][$field]['title'];
733 elseif ($query->_fields
['activity'][$field]['title']) {
734 $headerRows[] = $query->_fields
['activity'][$field]['title'];
737 elseif (array_key_exists($field, $contactRelationshipTypes)) {
739 foreach ($value as $relationField => $relationValue) {
740 // below block is same as primary block (duplicate)
741 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
742 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
743 $headerName = $field . '-' . $relationField;
746 if ($relationField == 'current_employer') {
747 $headerName = $field . '-' . 'current_employer';
750 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
754 $headerRows[] = $headerName;
756 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
758 elseif ($relationField == 'phone_type_id') {
759 $headerName = $field . '-' . 'Phone Type';
760 $headerRows[] = $headerName;
761 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
763 elseif ($relationField == 'provider_id') {
764 $headerName = $field . '-' . 'Im Service Provider';
765 $headerRows[] = $headerName;
766 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
768 elseif ($relationField == 'state_province_id') {
769 $headerName = $field . '-' . 'state_province_id';
770 $headerRows[] = $headerName;
771 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
773 elseif (is_array($relationValue) && $relationField == 'location') {
774 // fix header for location type case
775 foreach ($relationValue as $ltype => $val) {
776 foreach (array_keys($val) as $fld) {
777 $type = explode('-', $fld);
779 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
781 if (!empty($type[1])) {
782 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
783 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
785 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
786 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
789 $headerName = $field . '-' . $hdr;
790 $headerRows[] = $headerName;
791 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
797 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
798 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
801 $headerRows[] = $field;
805 self
::sqlColumnDefn($query, $sqlColumns, $field);
809 // add im_provider to $dao object
810 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
811 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
814 //build row values (data)
816 if (property_exists($iterationDAO, $field)) {
817 $fieldValue = $iterationDAO->$field;
818 // to get phone type from phone type id
819 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
820 $fieldValue = $phoneTypes[$fieldValue];
822 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
823 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
825 elseif ($field == 'participant_role_id') {
826 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
827 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
828 $viewRoles = array();
829 foreach (explode($sep, $iterationDAO->$field) as $k => $v) {
830 $viewRoles[] = $participantRoles[$v];
832 $fieldValue = implode(',', $viewRoles);
834 elseif ($field == 'master_id') {
835 $masterAddressId = NULL;
836 if (isset($iterationDAO->master_id
)) {
837 $masterAddressId = $iterationDAO->master_id
;
839 // get display name of contact that address is shared.
840 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id
);
844 if ($field == 'id') {
845 $row[$field] = $iterationDAO->contact_id
;
846 // special case for calculated field
848 elseif ($field == 'source_contact_id') {
849 $row[$field] = $iterationDAO->contact_id
;
851 elseif ($field == 'pledge_balance_amount') {
852 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
853 // special case for calculated field
855 elseif ($field == 'pledge_next_pay_amount') {
856 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
858 elseif (is_array($value) && $field == 'location') {
859 // fix header for location type case
860 foreach ($value as $ltype => $val) {
861 foreach (array_keys($val) as $fld) {
862 $type = explode('-', $fld);
863 $fldValue = "{$ltype}-" . $type[0];
864 // CRM-14076 - fix label to work as the query object expects
865 // FIXME: We should not be using labels as keys!
866 $daoField = CRM_Utils_String
::munge($ltype) . '-' . $type[0];
868 if (!empty($type[1])) {
869 $fldValue .= "-" . $type[1];
870 $daoField .= "-" . $type[1];
873 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
877 $row[$fldValue] = $i18n->crm_translate($iterationDAO->$daoField, array('context' => 'country'));
880 case 'state_province':
881 $row[$fldValue] = $i18n->crm_translate($iterationDAO->$daoField, array('context' => 'province'));
885 $imFieldvalue = $daoField . "-provider_id";
886 $row[$fldValue] = CRM_Utils_Array
::value($iterationDAO->$imFieldvalue, $imProviders);
890 $row[$fldValue] = $iterationDAO->$daoField;
896 elseif (array_key_exists($field, $contactRelationshipTypes)) {
897 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
898 $relationQuery[$field]->convertToPseudoNames($relDAO);
899 foreach ($value as $relationField => $relationValue) {
900 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
901 $fieldValue = $relDAO->$relationField;
902 if ($relationField == 'phone_type_id') {
903 $fieldValue = $phoneTypes[$relationValue];
905 elseif ($relationField == 'provider_id') {
906 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
910 elseif (is_object($relDAO) && in_array($relationField, array(
911 'email_greeting', 'postal_greeting', 'addressee'))) {
912 //special case for greeting replacement
913 $fldValue = "{$relationField}_display";
914 $fieldValue = $relDAO->$fldValue;
916 elseif ( is_object($relDAO) && $relationField == 'state_province' ) {
917 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
919 elseif ( is_object($relDAO) && $relationField == 'country' ) {
920 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
925 $field = $field . '_';
927 if (array_key_exists($relationField, $multipleSelectFields)) {
928 $param = array($relationField => $fieldValue);
929 $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
930 CRM_Core_OptionGroup
::lookupValues($param, $names, FALSE);
931 $fieldValue = $param[$relationField];
933 if (is_object($relDAO) && $relationField == 'id') {
934 $row[$field . $relationField] = $relDAO->contact_id
;
936 elseif (is_array( $relationValue ) && $relationField == 'location') {
937 foreach ($relationValue as $ltype => $val) {
938 foreach (array_keys($val) as $fld) {
939 $type = explode('-', $fld);
940 $fldValue = "{$ltype}-" . $type[0];
941 if (!empty($type[1])) {
942 $fldValue .= "-" . $type[1];
944 // CRM-3157: localise country, region (both have ‘country’ context)
945 // and state_province (‘province’ context)
947 case (!is_object($relDAO)):
948 $row[$field . '_' . $fldValue] = '';
951 case in_array('country', $type):
952 case in_array('world_region', $type):
953 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
954 array('context' => 'country')
958 case in_array('state_province', $type):
959 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
960 array('context' => 'province')
965 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
971 elseif (isset($fieldValue) && $fieldValue != '') {
972 //check for custom data
973 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
974 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
975 $relationQuery[$field]->_options
979 //normal relationship fields
980 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
981 switch ($relationField) {
984 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
987 case 'state_province':
988 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
992 $row[$field . $relationField] = $fieldValue;
998 // if relation field is empty or null
999 $row[$field . $relationField] = '';
1003 elseif (isset($fieldValue) &&
1006 //check for custom data
1007 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1008 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
1010 elseif (array_key_exists($field, $multipleSelectFields)) {
1011 //option group fixes
1012 $paramsNew = array($field => $fieldValue);
1013 if ($field == 'test_tutoring') {
1014 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
1015 // for readers group
1017 elseif (substr($field, 0, 4) == 'cmr_') {
1018 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
1021 $name = array($field => array('newName' => $field, 'groupName' => $field));
1023 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
1024 $row[$field] = $paramsNew[$field];
1027 elseif (in_array($field, array(
1028 'email_greeting', 'postal_greeting', 'addressee'))) {
1029 //special case for greeting replacement
1030 $fldValue = "{$field}_display";
1031 $row[$field] = $iterationDAO->$fldValue;
1034 //normal fields with a touch of CRM-3157
1037 case 'world_region':
1038 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1041 case 'state_province':
1042 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1046 case 'preferred_communication_method':
1047 case 'preferred_mail_format':
1048 case 'communication_style':
1049 $row[$field] = $i18n->crm_translate($fieldValue);
1053 $row[$field] = $fieldValue;
1058 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1059 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1060 $payFieldMapper = array(
1061 'componentPaymentField_total_amount' => 'total_amount',
1062 'componentPaymentField_contribution_status' => 'contribution_status',
1063 'componentPaymentField_payment_instrument' => 'pay_instru',
1064 'componentPaymentField_transaction_id' => 'trxn_id',
1065 'componentPaymentField_received_date' => 'receive_date',
1067 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1070 // if field is empty or null
1075 // add payment headers if required
1076 if ($addPaymentHeader && $paymentFields) {
1077 $headerRows = array_merge($headerRows, $paymentHeaders);
1078 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1079 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1084 $exportTempTable = self
::createTempTable($sqlColumns);
1087 //build header only once
1090 // If specific payment fields have been selected for export, payment
1091 // data will already be in $row. Otherwise, add payment related
1092 // information, if appropriate.
1093 if ($addPaymentHeader) {
1094 if (!$selectedPaymentFields) {
1095 if ($paymentFields) {
1096 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1097 if (!is_array($paymentData) ||
empty($paymentData)) {
1098 $paymentData = $nullContributionDetails;
1100 $row = array_merge($row, $paymentData);
1102 elseif (!empty($paymentDetails)) {
1103 $row = array_merge($row, $nullContributionDetails);
1107 //remove organization name for individuals if it is set for current employer
1108 if (!empty($row['contact_type']) &&
1109 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1111 $row['organization_name'] = '';
1114 // add component info
1115 // write the row to a file
1116 $componentDetails[] = $row;
1118 // output every $tempRowCount rows
1119 if ($count %
$tempRowCount == 0) {
1120 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1121 $componentDetails = array();
1125 $offset +
= $rowCount;
1128 if ($exportTempTable) {
1129 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1131 // do merge same address and merge same household processing
1132 if ($mergeSameAddress) {
1133 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1136 // merge the records if they have corresponding households
1137 if ($mergeSameHousehold) {
1138 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1139 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1142 // fix the headers for rows with relationship type
1143 if (!empty($relName)) {
1144 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1147 // if postalMailing option is checked, exclude contacts who are deceased, have
1148 // "Do not mail" privacy setting, or have no street address
1149 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1150 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1152 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1156 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1158 // now write the CSV file
1159 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1161 // delete the export temp table and component table
1162 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1163 CRM_Core_DAO
::executeQuery($sql);
1165 CRM_Utils_System
::civiExit();
1168 CRM_Core_Error
::fatal(ts('No records to export'));
1173 * Name of the export file based on mode
1175 * @param string $output type of output
1176 * @param int $mode export mode
1178 * @return string name of the file
1180 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1182 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1183 return ts('CiviCRM Contact Search');
1185 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1186 return ts('CiviCRM Contribution Search');
1188 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1189 return ts('CiviCRM Member Search');
1191 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1192 return ts('CiviCRM Participant Search');
1194 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1195 return ts('CiviCRM Pledge Search');
1197 case CRM_Export_Form_Select
::CASE_EXPORT
:
1198 return ts('CiviCRM Case Search');
1200 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1201 return ts('CiviCRM Grant Search');
1203 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1204 return ts('CiviCRM Activity Search');
1209 * Handle import error file creation.
1212 public static function invoke() {
1213 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1214 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1215 if (empty($parserName) ||
empty($type)) {
1219 // clean and ensure parserName is a valid string
1220 $parserName = CRM_Utils_String
::munge($parserName);
1221 $parserClass = explode('_', $parserName);
1223 // make sure parserClass is in the CRM namespace and
1224 // at least 3 levels deep
1225 if ($parserClass[0] == 'CRM' &&
1226 count($parserClass) >= 3
1228 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php");
1229 // ensure the functions exists
1230 if (method_exists($parserName, 'errorFileName') &&
1231 method_exists($parserName, 'saveFileName')
1233 $errorFileName = $parserName::errorFileName($type);
1234 $saveFileName = $parserName::saveFileName($type);
1235 if (!empty($errorFileName) && !empty($saveFileName)) {
1236 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1237 header('Content-Description: File Transfer');
1238 header('Content-Type: text/csv');
1239 header('Content-Length: ' . filesize($errorFileName));
1240 header('Content-Disposition: attachment; filename=' . $saveFileName);
1242 readfile($errorFileName);
1246 CRM_Utils_System
::civiExit();
1250 * @param $customSearchClass
1251 * @param $formValues
1254 public static function exportCustom($customSearchClass, $formValues, $order) {
1255 $ext = CRM_Extension_System
::singleton()->getMapper();
1256 if (!$ext->isExtensionClass($customSearchClass)) {
1257 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php');
1260 require_once ($ext->classToPath($customSearchClass));
1262 $search = new $customSearchClass($formValues);
1264 $includeContactIDs = FALSE;
1265 if ($formValues['radio_ts'] == 'ts_sel') {
1266 $includeContactIDs = TRUE;
1269 $sql = $search->all(0, 0, $order, $includeContactIDs);
1271 $columns = $search->columns();
1273 $header = array_keys($columns);
1274 $fields = array_values($columns);
1277 $dao = CRM_Core_DAO
::executeQuery($sql);
1279 if (method_exists($search, 'alterRow')) {
1282 while ($dao->fetch()) {
1285 foreach ($fields as $field) {
1286 $row[$field] = $dao->$field;
1289 $search->alterRow($row);
1294 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1295 CRM_Utils_System
::civiExit();
1300 * @param $sqlColumns
1303 public static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1304 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1308 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1309 if ($fieldName == 'id') {
1310 $fieldName = 'civicrm_primary_id';
1313 // early exit for master_id, CRM-12100
1314 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1315 if ($fieldName == 'master_id') {
1316 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1320 if (substr($fieldName, -11) == 'campaign_id') {
1322 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1323 $sqlColumns[$fieldName . '_id'] = "{$fieldName}_id varchar(16)";
1327 // set the sql columns
1328 if (isset($query->_fields
[$field]['type'])) {
1329 switch ($query->_fields
[$field]['type']) {
1330 case CRM_Utils_Type
::T_INT
:
1331 case CRM_Utils_Type
::T_BOOLEAN
:
1332 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1335 case CRM_Utils_Type
::T_STRING
:
1336 if (isset($query->_fields
[$field]['maxlength'])) {
1337 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1340 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1344 case CRM_Utils_Type
::T_TEXT
:
1345 case CRM_Utils_Type
::T_LONGTEXT
:
1346 case CRM_Utils_Type
::T_BLOB
:
1347 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1348 $sqlColumns[$fieldName] = "$fieldName longtext";
1351 case CRM_Utils_Type
::T_FLOAT
:
1352 case CRM_Utils_Type
::T_ENUM
:
1353 case CRM_Utils_Type
::T_DATE
:
1354 case CRM_Utils_Type
::T_TIME
:
1355 case CRM_Utils_Type
::T_TIMESTAMP
:
1356 case CRM_Utils_Type
::T_MONEY
:
1357 case CRM_Utils_Type
::T_EMAIL
:
1358 case CRM_Utils_Type
::T_URL
:
1359 case CRM_Utils_Type
::T_CCNUM
:
1361 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1366 if (substr($fieldName, -3, 3) == '_id') {
1367 // for trxn_id and its variants use a longer buffer
1368 // to accomodate different systems - CRM-13739
1369 static $notRealIDFields = NULL;
1370 if ($notRealIDFields == NULL) {
1371 $notRealIDFields = array( 'trxn_id', 'componentpaymentfield_transaction_id' );
1374 if (in_array($fieldName, $notRealIDFields)) {
1375 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1378 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1381 elseif (substr($fieldName, -5, 5) == '_note') {
1382 $sqlColumns[$fieldName] = "$fieldName text";
1385 $changeFields = array(
1391 if (in_array($fieldName, $changeFields)) {
1392 $sqlColumns[$fieldName] = "$fieldName text";
1395 // set the sql columns for custom data
1396 if (isset($query->_fields
[$field]['data_type'])) {
1398 switch ($query->_fields
[$field]['data_type']) {
1400 $length = empty($query->_fields
[$field]['text_length']) ?
255 : $query->_fields
[$field]['text_length'];
1401 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1405 case 'StateProvince':
1407 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1411 $sqlColumns[$fieldName] = "$fieldName text";
1415 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1420 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1428 * @param string $tableName
1430 * @param $sqlColumns
1432 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1433 if (empty($details)) {
1442 $id = CRM_Core_DAO
::singleValueQuery($sql);
1447 $sqlClause = array();
1449 foreach ($details as $dontCare => $row) {
1451 $valueString = array($id);
1452 foreach ($row as $dontCare => $value) {
1453 if (empty($value)) {
1454 $valueString[] = "''";
1457 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1460 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1463 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1465 $sqlValueString = implode(",\n", $sqlClause);
1468 INSERT INTO $tableName $sqlColumnString
1469 VALUES $sqlValueString
1472 CRM_Core_DAO
::executeQuery($sql);
1476 * @param $sqlColumns
1480 public static function createTempTable(&$sqlColumns) {
1481 //creating a temporary table for the search result that need be exported
1482 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1484 // also create the sql table
1485 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1486 CRM_Core_DAO
::executeQuery($sql);
1489 CREATE TABLE {$exportTempTable} (
1490 id int unsigned NOT NULL AUTO_INCREMENT,
1492 $sql .= implode(",\n", array_values($sqlColumns));
1497 // add indexes for street_address and household_name if present
1498 $addIndices = array(
1501 'civicrm_primary_id',
1504 foreach ($addIndices as $index) {
1505 if (isset($sqlColumns[$index])) {
1507 INDEX index_{$index}( $index )
1513 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1516 CRM_Core_DAO
::executeQuery($sql);
1517 return $exportTempTable;
1521 * @param string $tableName
1522 * @param $headerRows
1523 * @param $sqlColumns
1524 * @param array $exportParams
1526 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1527 // check if any records are present based on if they have used shared address feature,
1528 // and not based on if city / state .. matches.
1530 SELECT r1.id as copy_id,
1531 r1.civicrm_primary_id as copy_contact_id,
1532 r1.addressee as copy_addressee,
1533 r1.addressee_id as copy_addressee_id,
1534 r1.postal_greeting as copy_postal_greeting,
1535 r1.postal_greeting_id as copy_postal_greeting_id,
1537 r2.civicrm_primary_id as master_contact_id,
1538 r2.postal_greeting as master_postal_greeting,
1539 r2.postal_greeting_id as master_postal_greeting_id,
1540 r2.addressee as master_addressee,
1541 r2.addressee_id as master_addressee_id
1543 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1544 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1546 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1548 // find all the records that have the same street address BUT not in a household
1549 // require match on city and state as well
1551 SELECT r1.id as master_id,
1552 r1.civicrm_primary_id as master_contact_id,
1553 r1.postal_greeting as master_postal_greeting,
1554 r1.postal_greeting_id as master_postal_greeting_id,
1555 r1.addressee as master_addressee,
1556 r1.addressee_id as master_addressee_id,
1558 r2.civicrm_primary_id as copy_contact_id,
1559 r2.postal_greeting as copy_postal_greeting,
1560 r2.postal_greeting_id as copy_postal_greeting_id,
1561 r2.addressee as copy_addressee,
1562 r2.addressee_id as copy_addressee_id
1564 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1565 r1.city = r2.city AND
1566 r1.state_province_id = r2.state_province_id )
1567 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1568 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1569 AND ( r1.street_address != '' )
1573 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1575 // unset ids from $merge already present in $linkedMerge
1576 foreach ($linkedMerge as $masterID => $values) {
1577 $keys = array($masterID);
1578 $keys = array_merge($keys, array_keys($values['copy']));
1579 foreach ($merge as $mid => $vals) {
1580 if (in_array($mid, $keys)) {
1581 unset($merge[$mid]);
1584 foreach ($values['copy'] as $copyId) {
1585 if (in_array($copyId, $keys)) {
1586 unset($merge[$mid]['copy'][$copyId]);
1592 $merge = $merge +
$linkedMerge;
1594 foreach ($merge as $masterID => $values) {
1597 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1600 $params = array(1 => array($values['addressee'], 'String'),
1601 2 => array($values['postalGreeting'], 'String'),
1602 3 => array($values['emailGreeting'], 'String'),
1603 4 => array($masterID, 'Integer'),
1605 CRM_Core_DAO
::executeQuery($sql, $params);
1607 // delete all copies
1608 $deleteIDs = array_keys($values['copy']);
1609 $deleteIDString = implode(',', $deleteIDs);
1611 DELETE FROM $tableName
1612 WHERE id IN ( $deleteIDString )
1614 CRM_Core_DAO
::executeQuery($sql);
1617 // unset temporary columns that were added for postal mailing format
1618 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1619 $unsetKeys = array_keys($sqlColumns);
1620 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1621 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1622 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1629 * @param int $contactId
1630 * @param array $exportParams
1634 public static function _replaceMergeTokens($contactId, $exportParams) {
1635 $greetings = array();
1638 $greetingFields = array(
1642 foreach ($greetingFields as $greeting) {
1643 if (!empty($exportParams[$greeting])) {
1644 $greetingLabel = $exportParams[$greeting];
1645 if (empty($contact)) {
1650 $contact = civicrm_api('contact', 'get', $values);
1652 if (!empty($contact['is_error'])) {
1655 $contact = $contact['values'][$contact['id']];
1658 $tokens = array('contact' => $greetingLabel);
1659 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1666 * The function unsets static part of the string, if token is the dynamic part.
1667 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1668 * i.e 'Hello Alan' => converted to => 'Alan'
1671 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1672 $addressMergeGreetings, $greetingType = 'postal_greeting'
1674 if (!empty($addressMergeGreetings[$greetingType])) {
1675 $greetingLabel = $addressMergeGreetings[$greetingType];
1677 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1679 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1680 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1681 foreach ($stringsToBeReplaced as $key => $string) {
1682 // to keep one space
1683 $stringsToBeReplaced[$key] = ltrim($string);
1685 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1687 return $parsedString;
1692 * @param array $exportParams
1693 * @param bool $sharedAddress
1697 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1698 static $contactGreetingTokens = array();
1700 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1701 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1703 $merge = $parents = array();
1704 $dao = CRM_Core_DAO
::executeQuery($sql);
1706 while ($dao->fetch()) {
1707 $masterID = $dao->master_id
;
1708 $copyID = $dao->copy_id
;
1709 $masterPostalGreeting = $dao->master_postal_greeting
;
1710 $masterAddressee = $dao->master_addressee
;
1711 $copyAddressee = $dao->copy_addressee
;
1713 if (!$sharedAddress) {
1714 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1715 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1717 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1718 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1720 $masterAddressee = CRM_Utils_Array
::value('addressee',
1721 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1724 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1725 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1727 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1728 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1730 $copyAddressee = CRM_Utils_Array
::value('addressee',
1731 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1735 if (!isset($merge[$masterID])) {
1736 // check if this is an intermediate child
1737 // this happens if there are 3 or more matches a,b, c
1738 // the above query will return a, b / a, c / b, c
1739 // we might be doing a bit more work, but for now its ok, unless someone
1740 // knows how to fix the query above
1741 if (isset($parents[$masterID])) {
1742 $masterID = $parents[$masterID];
1745 $merge[$masterID] = array(
1746 'addressee' => $masterAddressee,
1748 'postalGreeting' => $masterPostalGreeting,
1750 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1753 $parents[$copyID] = $masterID;
1755 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1757 if (!empty($exportParams['postal_greeting_other']) &&
1758 count($merge[$masterID]['copy']) >= 1
1760 // use static greetings specified if no of contacts > 2
1761 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1763 elseif ($copyPostalGreeting) {
1764 self
::_trimNonTokens($copyPostalGreeting,
1765 $postalOptions[$dao->copy_postal_greeting_id
],
1768 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1769 // if there happens to be a duplicate, remove it
1770 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1773 if (!empty($exportParams['addressee_other']) &&
1774 count($merge[$masterID]['copy']) >= 1
1776 // use static greetings specified if no of contacts > 2
1777 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1779 elseif ($copyAddressee) {
1780 self
::_trimNonTokens($copyAddressee,
1781 $addresseeOptions[$dao->copy_addressee_id
],
1782 $exportParams, 'addressee'
1784 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1787 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1794 * Merge household record into the individual record
1797 * @param string $exportTempTable temporary temp table that stores the records
1798 * @param array $headerRows array of headers for the export file
1799 * @param array $sqlColumns array of names of the table columns of the temp table
1800 * @param string $prefix name of the relationship type that is prefixed to the table columns
1802 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1803 $prefixColumn = $prefix . '_';
1804 $allKeys = array_keys($sqlColumns);
1805 $replaced = array();
1806 $headerRows = array_values($headerRows);
1808 // name map of the non standard fields in header rows & sql columns
1809 $mappingFields = array(
1810 'civicrm_primary_id' => 'id',
1811 'contact_source' => 'source',
1812 'current_employer_id' => 'employer_id',
1813 'contact_is_deleted' => 'is_deleted',
1814 'name' => 'address_name',
1815 'provider_id' => 'im_service_provider',
1816 'phone_type_id' => 'phone_type'
1819 //figure out which columns are to be replaced by which ones
1820 foreach ($sqlColumns as $columnNames => $dontCare) {
1821 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1822 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1825 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1827 if (!empty($sqlColumns[$householdColName])) {
1828 $replaced[$columnNames] = $householdColName;
1832 $query = "UPDATE $exportTempTable SET ";
1835 foreach ($replaced as $from => $to) {
1836 $clause[] = "$from = $to ";
1837 unset($sqlColumns[$to]);
1838 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1839 unset($headerRows[$key]);
1842 $query .= implode(",\n", $clause);
1843 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1845 CRM_Core_DAO
::executeQuery($query);
1847 //drop the table columns that store redundant household info
1848 $dropQuery = "ALTER TABLE $exportTempTable ";
1849 foreach ($replaced as $householdColumns) {
1850 $dropClause[] = " DROP $householdColumns ";
1852 $dropQuery .= implode(",\n", $dropClause);
1854 CRM_Core_DAO
::executeQuery($dropQuery);
1856 // also drop the temp table if exists
1857 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1858 CRM_Core_DAO
::executeQuery($sql);
1860 // clean up duplicate records
1862 CREATE TABLE {$exportTempTable}_temp SELECT *
1863 FROM {$exportTempTable}
1864 GROUP BY civicrm_primary_id ";
1866 CRM_Core_DAO
::executeQuery($query);
1868 $query = "DROP TABLE $exportTempTable";
1869 CRM_Core_DAO
::executeQuery($query);
1871 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1872 CRM_Core_DAO
::executeQuery($query);
1876 * @param $exportTempTable
1877 * @param $headerRows
1878 * @param $sqlColumns
1879 * @param $exportMode
1880 * @param null $saveFile
1881 * @param string $batchItems
1883 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1884 $writeHeader = TRUE;
1886 $limit = self
::EXPORT_ROW_COUNT
;
1888 $query = "SELECT * FROM $exportTempTable";
1891 $limitQuery = $query . "
1892 LIMIT $offset, $limit
1894 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1900 $componentDetails = array();
1901 while ($dao->fetch()) {
1904 foreach ($sqlColumns as $column => $dontCare) {
1905 $row[$column] = $dao->$column;
1907 $componentDetails[] = $row;
1909 if ( $exportMode == 'financial' ) {
1910 $getExportFileName = 'CiviCRM Contribution Search';
1913 $getExportFileName =self
::getExportFileName( 'csv', $exportMode );
1915 $csvRows = CRM_Core_Report_Excel
::writeCSVFile( $getExportFileName,
1922 if ($saveFile && !empty($csvRows)) {
1923 $batchItems .= $csvRows;
1926 $writeHeader = false;
1932 * Manipulate header rows for relationship fields
1935 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1936 foreach ($headerRows as & $header) {
1937 $split = explode('-', $header);
1938 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1939 $split[0] = $relationTypeName;
1940 $header = implode('-', $split);
1946 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1947 * or have no street address
1950 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1951 $whereClause = array();
1953 if (array_key_exists('is_deceased', $sqlColumns)) {
1954 $whereClause[] = 'is_deceased = 1';
1957 if (array_key_exists('do_not_mail', $sqlColumns)) {
1958 $whereClause[] = 'do_not_mail = 1';
1961 if (array_key_exists('street_address', $sqlColumns)) {
1962 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1964 // check for supplemental_address_1
1965 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1966 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1967 'address_options', TRUE, NULL, TRUE
1969 if (!empty($addressOptions['supplemental_address_1'])) {
1970 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1971 // enclose it again, since we are doing an AND in between a set of ORs
1972 $addressWhereClause = "( $addressWhereClause )";
1976 $whereClause[] = $addressWhereClause;
1979 if (!empty($whereClause)) {
1980 $whereClause = implode(' OR ', $whereClause);
1983 FROM $exportTempTable
1984 WHERE {$whereClause}";
1985 CRM_Core_DAO
::singleValueQuery($query);
1988 // unset temporary columns that were added for postal mailing format
1989 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1990 $unsetKeys = array_keys($sqlColumns);
1991 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1992 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1993 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
2000 * Build componentPayment fields.
2002 public static function componentPaymentFields() {
2003 static $componentPaymentFields;
2004 if (!isset( $componentPaymentFields)) {
2005 $componentPaymentFields = array(
2006 'componentPaymentField_total_amount' => ts('Total Amount'),
2007 'componentPaymentField_contribution_status' => ts('Contribution Status'),
2008 'componentPaymentField_received_date' => ts('Received Date'),
2009 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
2010 'componentPaymentField_transaction_id' => ts('Transaction ID'),
2013 return $componentPaymentFields;