3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 the list the export fields.
49 * @param int $selectAll
50 * User preference while export.
53 * @param array $params
54 * Associated array of fields.
55 * @param string $order
57 * @param array $fields
58 * Associated array of fields.
59 * @param array $moreReturnProperties
60 * Additional return fields.
61 * @param int $exportMode
63 * @param string $componentClause
65 * @param string $componentTable
67 * @param bool $mergeSameAddress
68 * Merge records if they have same address.
69 * @param bool $mergeSameHousehold
70 * Merge records if they belong to the same household.
72 * @param array $exportParams
73 * @param string $queryOperator
76 public static function exportComponents(
82 $moreReturnProperties = NULL,
83 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
84 $componentClause = NULL,
85 $componentTable = NULL,
86 $mergeSameAddress = FALSE,
87 $mergeSameHousehold = FALSE,
88 $exportParams = array(),
89 $queryOperator = 'AND'
91 $headerRows = $returnProperties = array();
92 $primary = $paymentFields = $selectedPaymentFields = FALSE;
93 $origFields = $fields;
94 $relationField = NULL;
96 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
97 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
98 $contactRelationshipTypes = CRM_Contact_BAO_Relationship
::getContactRelationshipType(
107 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTACTS
;
109 switch ($exportMode) {
110 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
111 $queryMode = CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
;
114 case CRM_Export_Form_Select
::EVENT_EXPORT
:
115 $queryMode = CRM_Contact_BAO_Query
::MODE_EVENT
;
118 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
119 $queryMode = CRM_Contact_BAO_Query
::MODE_MEMBER
;
122 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
123 $queryMode = CRM_Contact_BAO_Query
::MODE_PLEDGE
;
126 case CRM_Export_Form_Select
::CASE_EXPORT
:
127 $queryMode = CRM_Contact_BAO_Query
::MODE_CASE
;
130 case CRM_Export_Form_Select
::GRANT_EXPORT
:
131 $queryMode = CRM_Contact_BAO_Query
::MODE_GRANT
;
134 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
135 $queryMode = CRM_Contact_BAO_Query
::MODE_ACTIVITY
;
139 //construct return properties
140 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
141 $locationTypeFields = array(
143 'supplemental_address_1',
144 'supplemental_address_2',
147 'postal_code_suffix',
157 foreach ($fields as $key => $value) {
158 $phoneTypeId = $imProviderId = NULL;
159 $relationshipTypes = $fieldName = CRM_Utils_Array
::value(1, $value);
163 // get phoneType id and IM service provider id separately
164 if ($fieldName == 'phone') {
165 $phoneTypeId = CRM_Utils_Array
::value(3, $value);
167 elseif ($fieldName == 'im') {
168 $imProviderId = CRM_Utils_Array
::value(3, $value);
171 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
172 if (!empty($value[2])) {
173 $relationField = CRM_Utils_Array
::value(2, $value);
174 if (trim(CRM_Utils_Array
::value(3, $value))) {
175 $relLocTypeId = CRM_Utils_Array
::value(3, $value);
178 $relLocTypeId = 'Primary';
181 if ($relationField == 'phone') {
182 $relPhoneTypeId = CRM_Utils_Array
::value(4, $value);
184 elseif ($relationField == 'im') {
185 $relIMProviderId = CRM_Utils_Array
::value(4, $value);
188 elseif (!empty($value[4])) {
189 $relationField = CRM_Utils_Array
::value(4, $value);
190 $relLocTypeId = CRM_Utils_Array
::value(5, $value);
191 if ($relationField == 'phone') {
192 $relPhoneTypeId = CRM_Utils_Array
::value(6, $value);
194 elseif ($relationField == 'im') {
195 $relIMProviderId = CRM_Utils_Array
::value(6, $value);
200 $contactType = CRM_Utils_Array
::value(0, $value);
201 $locTypeId = CRM_Utils_Array
::value(2, $value);
203 if ($relationField) {
204 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
205 if ($relPhoneTypeId) {
206 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
208 elseif ($relIMProviderId) {
209 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
212 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
214 $relPhoneTypeId = $relIMProviderId = NULL;
217 $returnProperties[$relationshipTypes][$relationField] = 1;
220 elseif (is_numeric($locTypeId)) {
222 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
224 elseif ($imProviderId) {
225 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
228 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
232 //hack to fix component fields
233 //revert mix of event_id and title
234 if ($fieldName == 'event_id') {
235 $returnProperties['event_id'] = 1;
238 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
239 array_key_exists($fieldName, self
::componentPaymentFields())
241 $selectedPaymentFields = TRUE;
242 $paymentTableId = 'participant_id';
243 $returnProperties[$fieldName] = 1;
246 $returnProperties[$fieldName] = 1;
251 // hack to add default returnproperty based on export mode
252 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
253 $returnProperties['contribution_id'] = 1;
255 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
256 $returnProperties['participant_id'] = 1;
257 if (!empty($returnProperties['participant_role'])) {
258 unset($returnProperties['participant_role']);
259 $returnProperties['participant_role_id'] = 1;
262 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
263 $returnProperties['membership_id'] = 1;
265 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
266 $returnProperties['pledge_id'] = 1;
268 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
269 $returnProperties['case_id'] = 1;
271 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
272 $returnProperties['grant_id'] = 1;
274 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
275 $returnProperties['activity_id'] = 1;
280 $fields = CRM_Contact_BAO_Contact
::exportableFields('All', TRUE, TRUE);
281 foreach ($fields as $key => $var) {
282 if ($key && (substr($key, 0, 6) != 'custom')) {
284 $returnProperties[$key] = 1;
289 $returnProperties['location_type'] = 1;
290 $returnProperties['im_provider'] = 1;
291 $returnProperties['phone_type_id'] = 1;
292 $returnProperties['provider_id'] = 1;
293 $returnProperties['current_employer'] = 1;
296 $extraReturnProperties = array();
297 $paymentFields = FALSE;
299 switch ($queryMode) {
300 case CRM_Contact_BAO_Query
::MODE_EVENT
:
301 $paymentFields = TRUE;
302 $paymentTableId = 'participant_id';
305 case CRM_Contact_BAO_Query
::MODE_MEMBER
:
306 $paymentFields = TRUE;
307 $paymentTableId = 'membership_id';
310 case CRM_Contact_BAO_Query
::MODE_PLEDGE
:
311 $extraReturnProperties = CRM_Pledge_BAO_Query
::extraReturnProperties($queryMode);
312 $paymentFields = TRUE;
313 $paymentTableId = 'pledge_payment_id';
316 case CRM_Contact_BAO_Query
::MODE_CASE
:
317 $extraReturnProperties = CRM_Case_BAO_Query
::extraReturnProperties($queryMode);
321 if ($queryMode != CRM_Contact_BAO_Query
::MODE_CONTACTS
) {
322 $componentReturnProperties = CRM_Contact_BAO_Query
::defaultReturnProperties($queryMode);
323 if ($queryMode == CRM_Contact_BAO_Query
::MODE_CONTRIBUTE
) {
324 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
325 $componentReturnProperties = array_merge(
326 $componentReturnProperties,
327 CRM_Contribute_BAO_Query
::softCreditReturnProperties(TRUE));
329 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
331 if (!empty($extraReturnProperties)) {
332 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
335 // unset non exportable fields for components
336 $nonExpoFields = array(
340 'contribution_status_id',
342 'pledge_payment_status_id',
344 foreach ($nonExpoFields as $value) {
345 unset($returnProperties[$value]);
350 if ($mergeSameAddress) {
351 //make sure the addressee fields are selected
352 //while using merge same address feature
353 $returnProperties['addressee'] = 1;
354 $returnProperties['postal_greeting'] = 1;
355 $returnProperties['email_greeting'] = 1;
356 $returnProperties['street_name'] = 1;
357 $returnProperties['household_name'] = 1;
358 $returnProperties['street_address'] = 1;
359 $returnProperties['city'] = 1;
360 $returnProperties['state_province'] = 1;
362 // some columns are required for assistance incase they are not already present
363 $exportParams['merge_same_address']['temp_columns'] = array();
364 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
365 foreach ($tempColumns as $column) {
366 if (!array_key_exists($column, $returnProperties)) {
367 $returnProperties[$column] = 1;
368 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
369 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
374 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
375 // If an Additional Group is selected, then all contacts in that group are
376 // added to the export set (filtering out duplicates).
378 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";
379 CRM_Core_DAO
::executeQuery($query);
382 if ($moreReturnProperties) {
384 if (!empty($moreReturnProperties['group'])) {
385 unset($moreReturnProperties['group']);
386 $moreReturnProperties['groups'] = 1;
388 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
391 $exportParams['postal_mailing_export']['temp_columns'] = array();
392 if ($exportParams['exportOption'] == 2 &&
393 isset($exportParams['postal_mailing_export']) &&
394 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
396 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
397 foreach ($postalColumns as $column) {
398 if (!array_key_exists($column, $returnProperties)) {
399 $returnProperties[$column] = 1;
400 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
405 // rectify params to what proximity search expects if there is a value for prox_distance
407 if (!empty($params)) {
408 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
411 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
412 FALSE, FALSE, $queryMode,
413 FALSE, TRUE, TRUE, NULL, $queryOperator
418 $query->_sort
= $order;
419 list($select, $from, $where, $having) = $query->query();
421 if ($mergeSameHousehold == 1) {
422 if (!$returnProperties['id']) {
423 $returnProperties['id'] = 1;
426 //also merge Head of Household
427 $relationKeyMOH = CRM_Utils_Array
::key('Household Member of', $contactRelationshipTypes);
428 $relationKeyHOH = CRM_Utils_Array
::key('Head of Household for', $contactRelationshipTypes);
430 foreach ($returnProperties as $key => $value) {
431 if (!array_key_exists($key, $contactRelationshipTypes)) {
432 $returnProperties[$relationKeyMOH][$key] = $value;
433 $returnProperties[$relationKeyHOH][$key] = $value;
437 unset($returnProperties[$relationKeyMOH]['location_type']);
438 unset($returnProperties[$relationKeyMOH]['im_provider']);
439 unset($returnProperties[$relationKeyHOH]['location_type']);
440 unset($returnProperties[$relationKeyHOH]['im_provider']);
443 $allRelContactArray = $relationQuery = array();
445 foreach ($contactRelationshipTypes as $rel => $dnt) {
446 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
447 $allRelContactArray[$rel] = array();
448 // build Query for each relationship
449 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
450 NULL, FALSE, FALSE, $queryMode
452 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
454 list($id, $direction) = explode('_', $rel, 2);
455 // identify the relationship direction
456 $contactA = 'contact_id_a';
457 $contactB = 'contact_id_b';
458 if ($direction == 'b_a') {
459 $contactA = 'contact_id_b';
460 $contactB = 'contact_id_a';
462 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
465 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
466 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
467 $query = "SELECT contact_id FROM civicrm_activity_contact
468 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
469 record_type_id = {$sourceID}";
470 $dao = CRM_Core_DAO
::executeQuery($query);
471 while ($dao->fetch()) {
472 $relIDs[] = $dao->contact_id
;
476 switch ($exportMode) {
477 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
478 $component = 'civicrm_contribution';
481 case CRM_Export_Form_Select
::EVENT_EXPORT
:
482 $component = 'civicrm_participant';
485 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
486 $component = 'civicrm_membership';
489 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
490 $component = 'civicrm_pledge';
493 case CRM_Export_Form_Select
::GRANT_EXPORT
:
494 $component = 'civicrm_grant';
498 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
499 $relIDs = CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
502 $relIDs = CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
506 $relationshipJoin = $relationshipClause = '';
507 if (!$selectAll && $componentTable) {
508 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
510 elseif (!empty($relIDs)) {
511 $relID = implode(',', $relIDs);
512 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
515 $relationFrom = " {$relationFrom}
516 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
517 {$relationshipJoin} ";
519 //check for active relationship status only
520 $today = date('Ymd');
521 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
522 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
523 $relationGroupBy = " GROUP BY crel.{$contactA}";
524 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
525 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
527 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
528 while ($allRelContactDAO->fetch()) {
529 //FIX Me: Migrate this to table rather than array
530 // build the array of all related contacts
531 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
533 $allRelContactDAO->free();
537 // make sure the groups stuff is included only if specifically specified
538 // by the fields param (CRM-1969), else we limit the contacts outputted to only
539 // ones that are part of a group
540 if (!empty($returnProperties['groups'])) {
541 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
542 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
543 // total hack for export, CRM-3618
544 $from = str_replace($oldClause,
550 if (!$selectAll && $componentTable) {
551 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
553 elseif ($componentClause) {
555 $where = "WHERE $componentClause";
558 $where .= " AND $componentClause";
562 // CRM-13982 - check if is deleted
563 $excludeTrashed = TRUE;
564 foreach ($params as $value) {
565 if ($value[0] == 'contact_is_deleted') {
566 $excludeTrashed = FALSE;
569 if (empty($where) && $excludeTrashed) {
570 $where = "WHERE contact_a.is_deleted != 1";
572 elseif ($excludeTrashed) {
573 $where .= " AND contact_a.is_deleted != 1";
576 $queryString = "$select $from $where $having";
579 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
580 CRM_Utils_Array
::value('notes', $returnProperties) ||
582 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
584 $groupBy = " GROUP BY contact_a.id";
587 switch ($exportMode) {
588 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
589 $groupBy = 'GROUP BY civicrm_contribution.id';
590 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
591 // especial group by when soft credit columns are included
592 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
596 case CRM_Export_Form_Select
::EVENT_EXPORT
:
597 $groupBy = 'GROUP BY civicrm_participant.id';
600 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
601 $groupBy = " GROUP BY civicrm_membership.id";
605 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
606 $groupBy = " GROUP BY civicrm_activity.id ";
608 $queryString .= $groupBy;
610 // always add contact_a.id to the ORDER clause
611 // so the order is deterministic
613 if (strpos('contact_a.id', $order) === FALSE) {
614 $order .= ", contact_a.id";
618 list($field, $dir) = explode(' ', $order, 2);
619 $field = trim($field);
620 if (!empty($returnProperties[$field])) {
622 $queryString .= " ORDER BY $order";
626 $multipleSelectFields = array('preferred_communication_method' => 1);
628 $addPaymentHeader = FALSE;
630 $paymentDetails = array();
631 if ($paymentFields ||
$selectedPaymentFields) {
633 // get payment related in for event and members
634 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
635 //get all payment headers.
636 // If we haven't selected specific payment fields, load in all the
638 if (!$selectedPaymentFields) {
639 $paymentHeaders = self
::componentPaymentFields();
640 if (!empty($paymentDetails)) {
641 $addPaymentHeader = TRUE;
644 // If we have selected specific payment fields, leave the payment headers
645 // as an empty array; the headers for each selected field will be added
648 $paymentHeaders = array();
650 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
653 $componentDetails = $headerRows = $sqlColumns = array();
656 $rowCount = self
::EXPORT_ROW_COUNT
;
658 // we write to temp table often to avoid using too much memory
663 // for CRM-3157 purposes
664 $i18n = CRM_Core_I18n
::singleton();
665 $outputColumns = array();
666 //@todo - it would be clearer to start defining output columns earlier in this function rather than stick with return properties until this point
667 // as the array is not actually 'returnProperties' after the sql query is formed - making the alterations to it confusing
668 foreach ($returnProperties as $key => $value) {
669 $outputColumns[$key] = $value;
672 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
673 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
678 while ($dao->fetch()) {
682 //convert the pseudo constants
683 // CRM-14398 there is problem in this architecture that is not easily solved. For now we are using the cloned
684 // temporary iterationDAO object to get around it.
685 // the issue is that the convertToPseudoNames function is adding additional properties (e.g for campaign) to the DAO object
686 // these additional properties are NOT reset when the $dao cycles through the while loop
687 // nor are they overwritten as they are not in the loop
688 // the convertToPseudoNames will not adequately over-write them either as it doesn't 'kick-in' unless the
689 // relevant property is set.
690 // It may be that a long-term fix could be introduced there - however, it's probably necessary to figure out how to test the
691 // export class before tackling a better architectural fix
692 $iterationDAO = clone $dao;
693 $query->convertToPseudoNames($iterationDAO);
695 //first loop through output columns so that we return what is required, and in same order.
696 $relationshipField = 0;
697 foreach ($outputColumns as $field => $value) {
698 //we should set header only once
701 // Split campaign into 2 fields for id and title
702 if (substr($field, -14) == 'campaign_title') {
703 $headerRows[] = ts('Campaign Title');
705 elseif (substr($field, -11) == 'campaign_id') {
706 $headerRows[] = ts('Campaign ID');
708 elseif (isset($query->_fields
[$field]['title'])) {
709 $headerRows[] = $query->_fields
[$field]['title'];
711 elseif ($field == 'phone_type_id') {
712 $headerRows[] = ts('Phone Type');
714 elseif ($field == 'provider_id') {
715 $headerRows[] = ts('IM Service Provider');
717 elseif (is_array($value) && $field == 'location') {
718 // fix header for location type case
719 foreach ($value as $ltype => $val) {
720 foreach (array_keys($val) as $fld) {
721 $type = explode('-', $fld);
722 $hdr = "{$ltype}-" . $query->_fields
[$type[0]]['title'];
724 if (!empty($type[1])) {
725 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
726 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
728 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
729 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
732 $headerRows[] = $hdr;
733 self
::sqlColumnDefn($query, $sqlColumns, $hdr);
738 elseif (substr($field, 0, 5) == 'case_') {
739 if ($query->_fields
['case'][$field]['title']) {
740 $headerRows[] = $query->_fields
['case'][$field]['title'];
742 elseif ($query->_fields
['activity'][$field]['title']) {
743 $headerRows[] = $query->_fields
['activity'][$field]['title'];
746 elseif (array_key_exists($field, $contactRelationshipTypes)) {
748 foreach ($value as $relationField => $relationValue) {
749 // below block is same as primary block (duplicate)
750 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
751 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
752 $headerName = $field . '-' . $relationField;
755 if ($relationField == 'current_employer') {
756 $headerName = $field . '-' . 'current_employer';
759 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
763 $headerRows[] = $headerName;
765 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
767 elseif ($relationField == 'phone_type_id') {
768 $headerName = $field . '-' . 'Phone Type';
769 $headerRows[] = $headerName;
770 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
772 elseif ($relationField == 'provider_id') {
773 $headerName = $field . '-' . 'Im Service Provider';
774 $headerRows[] = $headerName;
775 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
777 elseif ($relationField == 'state_province_id') {
778 $headerName = $field . '-' . 'state_province_id';
779 $headerRows[] = $headerName;
780 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
782 elseif (is_array($relationValue) && $relationField == 'location') {
783 // fix header for location type case
784 foreach ($relationValue as $ltype => $val) {
785 foreach (array_keys($val) as $fld) {
786 $type = explode('-', $fld);
788 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
790 if (!empty($type[1])) {
791 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
792 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
794 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
795 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
798 $headerName = $field . '-' . $hdr;
799 $headerRows[] = $headerName;
800 self
::sqlColumnDefn($query, $sqlColumns, $headerName);
806 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
807 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
810 $headerRows[] = $field;
814 self
::sqlColumnDefn($query, $sqlColumns, $field);
818 // add im_provider to $dao object
819 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
820 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
823 //build row values (data)
825 if (property_exists($iterationDAO, $field)) {
826 $fieldValue = $iterationDAO->$field;
827 // to get phone type from phone type id
828 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
829 $fieldValue = $phoneTypes[$fieldValue];
831 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
832 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
834 elseif ($field == 'participant_role_id') {
835 $participantRoles = CRM_Event_PseudoConstant
::participantRole();
836 $sep = CRM_Core_DAO
::VALUE_SEPARATOR
;
837 $viewRoles = array();
838 foreach (explode($sep, $iterationDAO->$field) as $k => $v) {
839 $viewRoles[] = $participantRoles[$v];
841 $fieldValue = implode(',', $viewRoles);
843 elseif ($field == 'master_id') {
844 $masterAddressId = NULL;
845 if (isset($iterationDAO->master_id
)) {
846 $masterAddressId = $iterationDAO->master_id
;
848 // get display name of contact that address is shared.
849 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId, $iterationDAO->contact_id
);
853 if ($field == 'id') {
854 $row[$field] = $iterationDAO->contact_id
;
855 // special case for calculated field
857 elseif ($field == 'source_contact_id') {
858 $row[$field] = $iterationDAO->contact_id
;
860 elseif ($field == 'pledge_balance_amount') {
861 $row[$field] = $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
862 // special case for calculated field
864 elseif ($field == 'pledge_next_pay_amount') {
865 $row[$field] = $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
867 elseif (is_array($value) && $field == 'location') {
868 // fix header for location type case
869 foreach ($value as $ltype => $val) {
870 foreach (array_keys($val) as $fld) {
871 $type = explode('-', $fld);
872 $fldValue = "{$ltype}-" . $type[0];
873 // CRM-14076 - fix label to work as the query object expects
874 // FIXME: We should not be using labels as keys!
875 $daoField = CRM_Utils_String
::munge($ltype) . '-' . $type[0];
877 if (!empty($type[1])) {
878 $fldValue .= "-" . $type[1];
879 $daoField .= "-" . $type[1];
882 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
886 $row[$fldValue] = $i18n->crm_translate($iterationDAO->$daoField, array('context' => 'country'));
889 case 'state_province':
890 $row[$fldValue] = $i18n->crm_translate($iterationDAO->$daoField, array('context' => 'province'));
894 $imFieldvalue = $daoField . "-provider_id";
895 $row[$fldValue] = CRM_Utils_Array
::value($iterationDAO->$imFieldvalue, $imProviders);
899 $row[$fldValue] = $iterationDAO->$daoField;
905 elseif (array_key_exists($field, $contactRelationshipTypes)) {
906 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
907 $relationQuery[$field]->convertToPseudoNames($relDAO);
908 foreach ($value as $relationField => $relationValue) {
909 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
910 $fieldValue = $relDAO->$relationField;
911 if ($relationField == 'phone_type_id') {
912 $fieldValue = $phoneTypes[$relationValue];
914 elseif ($relationField == 'provider_id') {
915 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
918 elseif (is_object($relDAO) && in_array($relationField, array(
924 //special case for greeting replacement
925 $fldValue = "{$relationField}_display";
926 $fieldValue = $relDAO->$fldValue;
929 elseif (is_object($relDAO) && $relationField == 'state_province') {
930 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
932 elseif (is_object($relDAO) && $relationField == 'country') {
933 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
938 $field = $field . '_';
940 if (array_key_exists($relationField, $multipleSelectFields)) {
941 $param = array($relationField => $fieldValue);
942 $names = array($relationField => array('newName' => $relationField, 'groupName' => $relationField));
943 CRM_Core_OptionGroup
::lookupValues($param, $names, FALSE);
944 $fieldValue = $param[$relationField];
946 if (is_object($relDAO) && $relationField == 'id') {
947 $row[$field . $relationField] = $relDAO->contact_id
;
949 elseif (is_array($relationValue) && $relationField == 'location') {
950 foreach ($relationValue as $ltype => $val) {
951 foreach (array_keys($val) as $fld) {
952 $type = explode('-', $fld);
953 $fldValue = "{$ltype}-" . $type[0];
954 if (!empty($type[1])) {
955 $fldValue .= "-" . $type[1];
957 // CRM-3157: localise country, region (both have ‘country’ context)
958 // and state_province (‘province’ context)
960 case (!is_object($relDAO)):
961 $row[$field . '_' . $fldValue] = '';
964 case in_array('country', $type):
965 case in_array('world_region', $type):
966 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
967 array('context' => 'country')
971 case in_array('state_province', $type):
972 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
973 array('context' => 'province')
978 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
984 elseif (isset($fieldValue) && $fieldValue != '') {
985 //check for custom data
986 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
987 $row[$field . $relationField] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID,
988 $relationQuery[$field]->_options
992 //normal relationship fields
993 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
994 switch ($relationField) {
997 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1000 case 'state_province':
1001 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1005 $row[$field . $relationField] = $fieldValue;
1011 // if relation field is empty or null
1012 $row[$field . $relationField] = '';
1016 elseif (isset($fieldValue) &&
1019 //check for custom data
1020 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1021 $row[$field] = CRM_Core_BAO_CustomField
::getDisplayValue($fieldValue, $cfID, $query->_options
);
1023 elseif (array_key_exists($field, $multipleSelectFields)) {
1024 //option group fixes
1025 $paramsNew = array($field => $fieldValue);
1026 if ($field == 'test_tutoring') {
1027 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
1028 // for readers group
1030 elseif (substr($field, 0, 4) == 'cmr_') {
1031 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
1034 $name = array($field => array('newName' => $field, 'groupName' => $field));
1036 CRM_Core_OptionGroup
::lookupValues($paramsNew, $name, FALSE);
1037 $row[$field] = $paramsNew[$field];
1040 elseif (in_array($field, array(
1045 //special case for greeting replacement
1046 $fldValue = "{$field}_display";
1047 $row[$field] = $iterationDAO->$fldValue;
1050 //normal fields with a touch of CRM-3157
1053 case 'world_region':
1054 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1057 case 'state_province':
1058 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1062 case 'preferred_communication_method':
1063 case 'preferred_mail_format':
1064 case 'communication_style':
1065 $row[$field] = $i18n->crm_translate($fieldValue);
1069 $row[$field] = $fieldValue;
1074 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1075 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1076 $payFieldMapper = array(
1077 'componentPaymentField_total_amount' => 'total_amount',
1078 'componentPaymentField_contribution_status' => 'contribution_status',
1079 'componentPaymentField_payment_instrument' => 'pay_instru',
1080 'componentPaymentField_transaction_id' => 'trxn_id',
1081 'componentPaymentField_received_date' => 'receive_date',
1083 $row[$field] = CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1086 // if field is empty or null
1091 // add payment headers if required
1092 if ($addPaymentHeader && $paymentFields) {
1093 $headerRows = array_merge($headerRows, $paymentHeaders);
1094 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1095 self
::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1100 $exportTempTable = self
::createTempTable($sqlColumns);
1103 //build header only once
1106 // If specific payment fields have been selected for export, payment
1107 // data will already be in $row. Otherwise, add payment related
1108 // information, if appropriate.
1109 if ($addPaymentHeader) {
1110 if (!$selectedPaymentFields) {
1111 if ($paymentFields) {
1112 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
1113 if (!is_array($paymentData) ||
empty($paymentData)) {
1114 $paymentData = $nullContributionDetails;
1116 $row = array_merge($row, $paymentData);
1118 elseif (!empty($paymentDetails)) {
1119 $row = array_merge($row, $nullContributionDetails);
1123 //remove organization name for individuals if it is set for current employer
1124 if (!empty($row['contact_type']) &&
1125 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1127 $row['organization_name'] = '';
1130 // add component info
1131 // write the row to a file
1132 $componentDetails[] = $row;
1134 // output every $tempRowCount rows
1135 if ($count %
$tempRowCount == 0) {
1136 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1137 $componentDetails = array();
1141 $offset +
= $rowCount;
1144 if ($exportTempTable) {
1145 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1147 // do merge same address and merge same household processing
1148 if ($mergeSameAddress) {
1149 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1152 // merge the records if they have corresponding households
1153 if ($mergeSameHousehold) {
1154 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1155 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1158 // fix the headers for rows with relationship type
1159 if (!empty($relName)) {
1160 self
::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1163 // if postalMailing option is checked, exclude contacts who are deceased, have
1164 // "Do not mail" privacy setting, or have no street address
1165 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1166 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1168 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1172 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1174 // now write the CSV file
1175 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1177 // delete the export temp table and component table
1178 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1179 CRM_Core_DAO
::executeQuery($sql);
1181 CRM_Utils_System
::civiExit();
1184 CRM_Core_Error
::fatal(ts('No records to export'));
1189 * Name of the export file based on mode.
1191 * @param string $output
1199 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1201 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
1202 return ts('CiviCRM Contact Search');
1204 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
1205 return ts('CiviCRM Contribution Search');
1207 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
1208 return ts('CiviCRM Member Search');
1210 case CRM_Export_Form_Select
::EVENT_EXPORT
:
1211 return ts('CiviCRM Participant Search');
1213 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
1214 return ts('CiviCRM Pledge Search');
1216 case CRM_Export_Form_Select
::CASE_EXPORT
:
1217 return ts('CiviCRM Case Search');
1219 case CRM_Export_Form_Select
::GRANT_EXPORT
:
1220 return ts('CiviCRM Grant Search');
1222 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
1223 return ts('CiviCRM Activity Search');
1228 * Handle import error file creation.
1230 public static function invoke() {
1231 $type = CRM_Utils_Request
::retrieve('type', 'Positive', CRM_Core_DAO
::$_nullObject);
1232 $parserName = CRM_Utils_Request
::retrieve('parser', 'String', CRM_Core_DAO
::$_nullObject);
1233 if (empty($parserName) ||
empty($type)) {
1237 // clean and ensure parserName is a valid string
1238 $parserName = CRM_Utils_String
::munge($parserName);
1239 $parserClass = explode('_', $parserName);
1241 // make sure parserClass is in the CRM namespace and
1242 // at least 3 levels deep
1243 if ($parserClass[0] == 'CRM' &&
1244 count($parserClass) >= 3
1246 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
1247 // ensure the functions exists
1248 if (method_exists($parserName, 'errorFileName') &&
1249 method_exists($parserName, 'saveFileName')
1251 $errorFileName = $parserName::errorFileName($type);
1252 $saveFileName = $parserName::saveFileName($type);
1253 if (!empty($errorFileName) && !empty($saveFileName)) {
1254 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
1255 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
1256 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
1257 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
1258 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
1260 readfile($errorFileName);
1264 CRM_Utils_System
::civiExit();
1268 * @param $customSearchClass
1269 * @param $formValues
1272 public static function exportCustom($customSearchClass, $formValues, $order) {
1273 $ext = CRM_Extension_System
::singleton()->getMapper();
1274 if (!$ext->isExtensionClass($customSearchClass)) {
1275 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
1278 require_once $ext->classToPath($customSearchClass);
1280 $search = new $customSearchClass($formValues);
1282 $includeContactIDs = FALSE;
1283 if ($formValues['radio_ts'] == 'ts_sel') {
1284 $includeContactIDs = TRUE;
1287 $sql = $search->all(0, 0, $order, $includeContactIDs);
1289 $columns = $search->columns();
1291 $header = array_keys($columns);
1292 $fields = array_values($columns);
1295 $dao = CRM_Core_DAO
::executeQuery($sql);
1297 if (method_exists($search, 'alterRow')) {
1300 while ($dao->fetch()) {
1303 foreach ($fields as $field) {
1304 $row[$field] = $dao->$field;
1307 $search->alterRow($row);
1312 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
1313 CRM_Utils_System
::civiExit();
1318 * @param $sqlColumns
1321 public static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
1322 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
1326 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
1327 if ($fieldName == 'id') {
1328 $fieldName = 'civicrm_primary_id';
1331 // early exit for master_id, CRM-12100
1332 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1333 if ($fieldName == 'master_id') {
1334 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1338 if (substr($fieldName, -11) == 'campaign_id') {
1340 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1344 $lookUp = array('prefix_id', 'suffix_id');
1345 // set the sql columns
1346 if (isset($query->_fields
[$field]['type'])) {
1347 switch ($query->_fields
[$field]['type']) {
1348 case CRM_Utils_Type
::T_INT
:
1349 case CRM_Utils_Type
::T_BOOLEAN
:
1350 if (in_array($field, $lookUp)) {
1351 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1354 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1358 case CRM_Utils_Type
::T_STRING
:
1359 if (isset($query->_fields
[$field]['maxlength'])) {
1360 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1363 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1367 case CRM_Utils_Type
::T_TEXT
:
1368 case CRM_Utils_Type
::T_LONGTEXT
:
1369 case CRM_Utils_Type
::T_BLOB
:
1370 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1371 $sqlColumns[$fieldName] = "$fieldName longtext";
1374 case CRM_Utils_Type
::T_FLOAT
:
1375 case CRM_Utils_Type
::T_ENUM
:
1376 case CRM_Utils_Type
::T_DATE
:
1377 case CRM_Utils_Type
::T_TIME
:
1378 case CRM_Utils_Type
::T_TIMESTAMP
:
1379 case CRM_Utils_Type
::T_MONEY
:
1380 case CRM_Utils_Type
::T_EMAIL
:
1381 case CRM_Utils_Type
::T_URL
:
1382 case CRM_Utils_Type
::T_CCNUM
:
1384 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1389 if (substr($fieldName, -3, 3) == '_id') {
1390 // for trxn_id and its variants use a longer buffer
1391 // to accommodate different systems - CRM-13739
1392 static $notRealIDFields = NULL;
1393 if ($notRealIDFields == NULL) {
1394 $notRealIDFields = array('trxn_id', 'componentpaymentfield_transaction_id');
1397 if (in_array($fieldName, $notRealIDFields)) {
1398 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1401 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1404 elseif (substr($fieldName, -5, 5) == '_note') {
1405 $sqlColumns[$fieldName] = "$fieldName text";
1408 $changeFields = array(
1414 if (in_array($fieldName, $changeFields)) {
1415 $sqlColumns[$fieldName] = "$fieldName text";
1418 // set the sql columns for custom data
1419 if (isset($query->_fields
[$field]['data_type'])) {
1421 switch ($query->_fields
[$field]['data_type']) {
1423 $length = empty($query->_fields
[$field]['text_length']) ?
255 : $query->_fields
[$field]['text_length'];
1424 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
1428 case 'StateProvince':
1430 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1434 $sqlColumns[$fieldName] = "$fieldName text";
1438 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1443 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1451 * @param string $tableName
1453 * @param $sqlColumns
1455 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1456 if (empty($details)) {
1465 $id = CRM_Core_DAO
::singleValueQuery($sql);
1470 $sqlClause = array();
1472 foreach ($details as $dontCare => $row) {
1474 $valueString = array($id);
1475 foreach ($row as $dontCare => $value) {
1476 if (empty($value)) {
1477 $valueString[] = "''";
1480 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
1483 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1486 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1488 $sqlValueString = implode(",\n", $sqlClause);
1491 INSERT INTO $tableName $sqlColumnString
1492 VALUES $sqlValueString
1495 CRM_Core_DAO
::executeQuery($sql);
1499 * @param $sqlColumns
1503 public static function createTempTable(&$sqlColumns) {
1504 //creating a temporary table for the search result that need be exported
1505 $exportTempTable = CRM_Core_DAO
::createTempTableName('civicrm_export', TRUE);
1507 // also create the sql table
1508 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1509 CRM_Core_DAO
::executeQuery($sql);
1512 CREATE TABLE {$exportTempTable} (
1513 id int unsigned NOT NULL AUTO_INCREMENT,
1515 $sql .= implode(",\n", array_values($sqlColumns));
1520 // add indexes for street_address and household_name if present
1521 $addIndices = array(
1524 'civicrm_primary_id',
1527 foreach ($addIndices as $index) {
1528 if (isset($sqlColumns[$index])) {
1530 INDEX index_{$index}( $index )
1536 ) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1539 CRM_Core_DAO
::executeQuery($sql);
1540 return $exportTempTable;
1544 * @param string $tableName
1545 * @param $headerRows
1546 * @param $sqlColumns
1547 * @param array $exportParams
1549 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1550 // check if any records are present based on if they have used shared address feature,
1551 // and not based on if city / state .. matches.
1553 SELECT r1.id as copy_id,
1554 r1.civicrm_primary_id as copy_contact_id,
1555 r1.addressee as copy_addressee,
1556 r1.addressee_id as copy_addressee_id,
1557 r1.postal_greeting as copy_postal_greeting,
1558 r1.postal_greeting_id as copy_postal_greeting_id,
1560 r2.civicrm_primary_id as master_contact_id,
1561 r2.postal_greeting as master_postal_greeting,
1562 r2.postal_greeting_id as master_postal_greeting_id,
1563 r2.addressee as master_addressee,
1564 r2.addressee_id as master_addressee_id
1566 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1567 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1569 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1571 // find all the records that have the same street address BUT not in a household
1572 // require match on city and state as well
1574 SELECT r1.id as master_id,
1575 r1.civicrm_primary_id as master_contact_id,
1576 r1.postal_greeting as master_postal_greeting,
1577 r1.postal_greeting_id as master_postal_greeting_id,
1578 r1.addressee as master_addressee,
1579 r1.addressee_id as master_addressee_id,
1581 r2.civicrm_primary_id as copy_contact_id,
1582 r2.postal_greeting as copy_postal_greeting,
1583 r2.postal_greeting_id as copy_postal_greeting_id,
1584 r2.addressee as copy_addressee,
1585 r2.addressee_id as copy_addressee_id
1587 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1588 r1.city = r2.city AND
1589 r1.state_province_id = r2.state_province_id )
1590 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1591 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1592 AND ( r1.street_address != '' )
1596 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1598 // unset ids from $merge already present in $linkedMerge
1599 foreach ($linkedMerge as $masterID => $values) {
1600 $keys = array($masterID);
1601 $keys = array_merge($keys, array_keys($values['copy']));
1602 foreach ($merge as $mid => $vals) {
1603 if (in_array($mid, $keys)) {
1604 unset($merge[$mid]);
1607 foreach ($values['copy'] as $copyId) {
1608 if (in_array($copyId, $keys)) {
1609 unset($merge[$mid]['copy'][$copyId]);
1615 $merge = $merge +
$linkedMerge;
1617 foreach ($merge as $masterID => $values) {
1620 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1624 1 => array($values['addressee'], 'String'),
1625 2 => array($values['postalGreeting'], 'String'),
1626 3 => array($values['emailGreeting'], 'String'),
1627 4 => array($masterID, 'Integer'),
1629 CRM_Core_DAO
::executeQuery($sql, $params);
1631 // delete all copies
1632 $deleteIDs = array_keys($values['copy']);
1633 $deleteIDString = implode(',', $deleteIDs);
1635 DELETE FROM $tableName
1636 WHERE id IN ( $deleteIDString )
1638 CRM_Core_DAO
::executeQuery($sql);
1641 // unset temporary columns that were added for postal mailing format
1642 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1643 $unsetKeys = array_keys($sqlColumns);
1644 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1645 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1646 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1653 * @param int $contactId
1654 * @param array $exportParams
1658 public static function _replaceMergeTokens($contactId, $exportParams) {
1659 $greetings = array();
1662 $greetingFields = array(
1666 foreach ($greetingFields as $greeting) {
1667 if (!empty($exportParams[$greeting])) {
1668 $greetingLabel = $exportParams[$greeting];
1669 if (empty($contact)) {
1674 $contact = civicrm_api('contact', 'get', $values);
1676 if (!empty($contact['is_error'])) {
1679 $contact = $contact['values'][$contact['id']];
1682 $tokens = array('contact' => $greetingLabel);
1683 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1690 * The function unsets static part of the string, if token is the dynamic part.
1691 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1692 * i.e 'Hello Alan' => converted to => 'Alan'
1694 public static function _trimNonTokens(
1695 &$parsedString, $defaultGreeting,
1696 $addressMergeGreetings, $greetingType = 'postal_greeting'
1698 if (!empty($addressMergeGreetings[$greetingType])) {
1699 $greetingLabel = $addressMergeGreetings[$greetingType];
1701 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1703 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1704 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1705 foreach ($stringsToBeReplaced as $key => $string) {
1706 // to keep one space
1707 $stringsToBeReplaced[$key] = ltrim($string);
1709 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1711 return $parsedString;
1716 * @param array $exportParams
1717 * @param bool $sharedAddress
1721 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1722 static $contactGreetingTokens = array();
1724 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1725 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1727 $merge = $parents = array();
1728 $dao = CRM_Core_DAO
::executeQuery($sql);
1730 while ($dao->fetch()) {
1731 $masterID = $dao->master_id
;
1732 $copyID = $dao->copy_id
;
1733 $masterPostalGreeting = $dao->master_postal_greeting
;
1734 $masterAddressee = $dao->master_addressee
;
1735 $copyAddressee = $dao->copy_addressee
;
1737 if (!$sharedAddress) {
1738 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1739 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1741 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1742 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1744 $masterAddressee = CRM_Utils_Array
::value('addressee',
1745 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1748 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1749 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1751 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1752 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1754 $copyAddressee = CRM_Utils_Array
::value('addressee',
1755 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1759 if (!isset($merge[$masterID])) {
1760 // check if this is an intermediate child
1761 // this happens if there are 3 or more matches a,b, c
1762 // the above query will return a, b / a, c / b, c
1763 // we might be doing a bit more work, but for now its ok, unless someone
1764 // knows how to fix the query above
1765 if (isset($parents[$masterID])) {
1766 $masterID = $parents[$masterID];
1769 $merge[$masterID] = array(
1770 'addressee' => $masterAddressee,
1772 'postalGreeting' => $masterPostalGreeting,
1774 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1777 $parents[$copyID] = $masterID;
1779 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1781 if (!empty($exportParams['postal_greeting_other']) &&
1782 count($merge[$masterID]['copy']) >= 1
1784 // use static greetings specified if no of contacts > 2
1785 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1787 elseif ($copyPostalGreeting) {
1788 self
::_trimNonTokens($copyPostalGreeting,
1789 $postalOptions[$dao->copy_postal_greeting_id
],
1792 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1793 // if there happens to be a duplicate, remove it
1794 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1797 if (!empty($exportParams['addressee_other']) &&
1798 count($merge[$masterID]['copy']) >= 1
1800 // use static greetings specified if no of contacts > 2
1801 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1803 elseif ($copyAddressee) {
1804 self
::_trimNonTokens($copyAddressee,
1805 $addresseeOptions[$dao->copy_addressee_id
],
1806 $exportParams, 'addressee'
1808 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1811 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1818 * Merge household record into the individual record
1821 * @param string $exportTempTable
1822 * Temporary temp table that stores the records.
1823 * @param array $headerRows
1824 * Array of headers for the export file.
1825 * @param array $sqlColumns
1826 * Array of names of the table columns of the temp table.
1827 * @param string $prefix
1828 * Name of the relationship type that is prefixed to the table columns.
1830 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1831 $prefixColumn = $prefix . '_';
1832 $allKeys = array_keys($sqlColumns);
1833 $replaced = array();
1834 $headerRows = array_values($headerRows);
1836 // name map of the non standard fields in header rows & sql columns
1837 $mappingFields = array(
1838 'civicrm_primary_id' => 'id',
1839 'contact_source' => 'source',
1840 'current_employer_id' => 'employer_id',
1841 'contact_is_deleted' => 'is_deleted',
1842 'name' => 'address_name',
1843 'provider_id' => 'im_service_provider',
1844 'phone_type_id' => 'phone_type',
1847 //figure out which columns are to be replaced by which ones
1848 foreach ($sqlColumns as $columnNames => $dontCare) {
1849 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1850 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1853 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1855 if (!empty($sqlColumns[$householdColName])) {
1856 $replaced[$columnNames] = $householdColName;
1860 $query = "UPDATE $exportTempTable SET ";
1863 foreach ($replaced as $from => $to) {
1864 $clause[] = "$from = $to ";
1865 unset($sqlColumns[$to]);
1866 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1867 unset($headerRows[$key]);
1870 $query .= implode(",\n", $clause);
1871 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1873 CRM_Core_DAO
::executeQuery($query);
1875 //drop the table columns that store redundant household info
1876 $dropQuery = "ALTER TABLE $exportTempTable ";
1877 foreach ($replaced as $householdColumns) {
1878 $dropClause[] = " DROP $householdColumns ";
1880 $dropQuery .= implode(",\n", $dropClause);
1882 CRM_Core_DAO
::executeQuery($dropQuery);
1884 // also drop the temp table if exists
1885 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1886 CRM_Core_DAO
::executeQuery($sql);
1888 // clean up duplicate records
1890 CREATE TABLE {$exportTempTable}_temp SELECT *
1891 FROM {$exportTempTable}
1892 GROUP BY civicrm_primary_id ";
1894 CRM_Core_DAO
::executeQuery($query);
1896 $query = "DROP TABLE $exportTempTable";
1897 CRM_Core_DAO
::executeQuery($query);
1899 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1900 CRM_Core_DAO
::executeQuery($query);
1904 * @param $exportTempTable
1905 * @param $headerRows
1906 * @param $sqlColumns
1907 * @param $exportMode
1908 * @param null $saveFile
1909 * @param string $batchItems
1911 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1912 $writeHeader = TRUE;
1914 $limit = self
::EXPORT_ROW_COUNT
;
1916 $query = "SELECT * FROM $exportTempTable";
1919 $limitQuery = $query . "
1920 LIMIT $offset, $limit
1922 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1928 $componentDetails = array();
1929 while ($dao->fetch()) {
1932 foreach ($sqlColumns as $column => $dontCare) {
1933 $row[$column] = $dao->$column;
1935 $componentDetails[] = $row;
1937 if ($exportMode == 'financial') {
1938 $getExportFileName = 'CiviCRM Contribution Search';
1941 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1943 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1950 if ($saveFile && !empty($csvRows)) {
1951 $batchItems .= $csvRows;
1954 $writeHeader = FALSE;
1960 * Manipulate header rows for relationship fields.
1962 * @param $headerRows
1963 * @param $contactRelationshipTypes
1965 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
1966 foreach ($headerRows as & $header) {
1967 $split = explode('-', $header);
1968 if ($relationTypeName = CRM_Utils_Array
::value($split[0], $contactRelationshipTypes)) {
1969 $split[0] = $relationTypeName;
1970 $header = implode('-', $split);
1976 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1977 * or have no street address
1978 * @param $exportTempTable
1979 * @param $headerRows
1980 * @param $sqlColumns
1981 * @param $exportParams
1983 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1984 $whereClause = array();
1986 if (array_key_exists('is_deceased', $sqlColumns)) {
1987 $whereClause[] = 'is_deceased = 1';
1990 if (array_key_exists('do_not_mail', $sqlColumns)) {
1991 $whereClause[] = 'do_not_mail = 1';
1994 if (array_key_exists('street_address', $sqlColumns)) {
1995 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1997 // check for supplemental_address_1
1998 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1999 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
2000 'address_options', TRUE, NULL, TRUE
2002 if (!empty($addressOptions['supplemental_address_1'])) {
2003 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
2004 // enclose it again, since we are doing an AND in between a set of ORs
2005 $addressWhereClause = "( $addressWhereClause )";
2009 $whereClause[] = $addressWhereClause;
2012 if (!empty($whereClause)) {
2013 $whereClause = implode(' OR ', $whereClause);
2016 FROM $exportTempTable
2017 WHERE {$whereClause}";
2018 CRM_Core_DAO
::singleValueQuery($query);
2021 // unset temporary columns that were added for postal mailing format
2022 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
2023 $unsetKeys = array_keys($sqlColumns);
2024 foreach ($unsetKeys as $headerKey => $sqlColKey) {
2025 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
2026 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
2033 * Build componentPayment fields.
2035 public static function componentPaymentFields() {
2036 static $componentPaymentFields;
2037 if (!isset($componentPaymentFields)) {
2038 $componentPaymentFields = array(
2039 'componentPaymentField_total_amount' => ts('Total Amount'),
2040 'componentPaymentField_contribution_status' => ts('Contribution Status'),
2041 'componentPaymentField_received_date' => ts('Date Received'),
2042 'componentPaymentField_payment_instrument' => ts('Payment Method'),
2043 'componentPaymentField_transaction_id' => ts('Transaction ID'),
2046 return $componentPaymentFields;