Make `formal_title` field optional
[civicrm-core.git] / CRM / Export / BAO / Export.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
232624b1 4 | CiviCRM version 4.4 |
6a488035
TO
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26*/
27
28/**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35
36/**
37 * This class contains the funtions for Component export
38 *
39 */
40class 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
43 // CRM-7675
44 CONST EXPORT_ROW_COUNT = 10000;
45
46 /**
47 * Function to get the list the export fields
48 *
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
60 *
61 * @static
62 * @access public
63 */
64 static function exportComponents($selectAll,
65 $ids,
66 $params,
67 $order = NULL,
68 $fields = NULL,
69 $moreReturnProperties = NULL,
70 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
71 $componentClause = NULL,
72 $componentTable = NULL,
73 $mergeSameAddress = FALSE,
74 $mergeSameHousehold = FALSE,
75 $exportParams = array(),
76 $queryOperator = 'AND'
77 ) {
78 $headerRows = $returnProperties = array();
d77aba4b 79 $primary = $paymentFields = $selectedPaymentFields = FALSE;
6a488035
TO
80 $origFields = $fields;
81 $queryMode = $relationField = NULL;
82
83 $allCampaigns = array();
84 $exportCampaign = FALSE;
85
b4f964d9 86 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
e7e657f0 87 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
6a488035
TO
88 $contactRelationshipTypes = CRM_Contact_BAO_Relationship::getContactRelationshipType(
89 NULL,
90 NULL,
91 NULL,
92 NULL,
93 TRUE,
545285b8 94 'name',
6a488035
TO
95 FALSE
96 );
97 $queryMode = CRM_Contact_BAO_Query::MODE_CONTACTS;
98
99 switch ($exportMode) {
100 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
101 $queryMode = CRM_Contact_BAO_Query::MODE_CONTRIBUTE;
102 break;
103
104 case CRM_Export_Form_Select::EVENT_EXPORT:
105 $queryMode = CRM_Contact_BAO_Query::MODE_EVENT;
106 break;
107
108 case CRM_Export_Form_Select::MEMBER_EXPORT:
109 $queryMode = CRM_Contact_BAO_Query::MODE_MEMBER;
110 break;
111
112 case CRM_Export_Form_Select::PLEDGE_EXPORT:
113 $queryMode = CRM_Contact_BAO_Query::MODE_PLEDGE;
114 break;
115
116 case CRM_Export_Form_Select::CASE_EXPORT:
117 $queryMode = CRM_Contact_BAO_Query::MODE_CASE;
118 break;
119
120 case CRM_Export_Form_Select::GRANT_EXPORT:
121 $queryMode = CRM_Contact_BAO_Query::MODE_GRANT;
122 break;
123
124 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
125 $queryMode = CRM_Contact_BAO_Query::MODE_ACTIVITY;
126 break;
127 }
128 if ($fields) {
129 //construct return properties
b2b0530a 130 $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
6a488035
TO
131 $locationTypeFields = array(
132 'street_address',
133 'supplemental_address_1',
134 'supplemental_address_2',
135 'city',
136 'postal_code',
137 'postal_code_suffix',
138 'geo_code_1',
139 'geo_code_2',
140 'state_province',
141 'country',
142 'phone',
143 'email',
144 'im',
145 );
146
147 foreach ($fields as $key => $value) {
148 $phoneTypeId = $imProviderId = NULL;
149 $relationshipTypes = $fieldName = CRM_Utils_Array::value(1, $value);
150 if (!$fieldName) {
151 continue;
152 }
153 // get phoneType id and IM service provider id seperately
154 if ($fieldName == 'phone') {
155 $phoneTypeId = CRM_Utils_Array::value(3, $value);
156 }
157 elseif ($fieldName == 'im') {
158 $imProviderId = CRM_Utils_Array::value(3, $value);
159 }
160 elseif (substr($fieldName, -8) == 'campaign') {
161 $exportCampaign = TRUE;
162 }
163
164 if (array_key_exists($relationshipTypes, $contactRelationshipTypes)) {
165 if (CRM_Utils_Array::value(2, $value)) {
166 $relationField = CRM_Utils_Array::value(2, $value);
167 if (trim(CRM_Utils_Array::value(3, $value))) {
168 $relLocTypeId = CRM_Utils_Array::value(3, $value);
169 }
170 else {
171 $relLocTypeId = 'Primary';
172 }
173
174 if ($relationField == 'phone') {
175 $relPhoneTypeId = CRM_Utils_Array::value(4, $value);
176 }
177 elseif ($relationField == 'im') {
178 $relIMProviderId = CRM_Utils_Array::value(4, $value);
179 }
180 }
181 elseif (CRM_Utils_Array::value(4, $value)) {
182 $relationField = CRM_Utils_Array::value(4, $value);
183 $relLocTypeId = CRM_Utils_Array::value(5, $value);
184 if ($relationField == 'phone') {
185 $relPhoneTypeId = CRM_Utils_Array::value(6, $value);
186 }
187 elseif ($relationField == 'im') {
188 $relIMProviderId = CRM_Utils_Array::value(6, $value);
189 }
190 }
191 }
192
193 $contactType = CRM_Utils_Array::value(0, $value);
194 $locTypeId = CRM_Utils_Array::value(2, $value);
195
196 if ($relationField) {
197 if (in_array($relationField, $locationTypeFields) && is_numeric($relLocTypeId)) {
198 if ($relPhoneTypeId) {
199 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['phone-' . $relPhoneTypeId] = 1;
200 }
201 elseif ($relIMProviderId) {
202 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]]['im-' . $relIMProviderId] = 1;
203 }
204 else {
205 $returnProperties[$relationshipTypes]['location'][$locationTypes[$relLocTypeId]][$relationField] = 1;
206 }
207 $relPhoneTypeId = $relIMProviderId = NULL;
208 }
209 else {
210 $returnProperties[$relationshipTypes][$relationField] = 1;
211 }
212 }
213 elseif (is_numeric($locTypeId)) {
214 if ($phoneTypeId) {
215 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . $phoneTypeId] = 1;
216 }
217 elseif ($imProviderId) {
218 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . $imProviderId] = 1;
219 }
220 else {
221 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
222 }
223 }
224 else {
225 //hack to fix component fields
226 if ($fieldName == 'event_id') {
227 $returnProperties['event_title'] = 1;
228 }
d77aba4b 229 else if (
545285b8 230 $exportMode == CRM_Export_Form_Select::EVENT_EXPORT &&
d77aba4b 231 array_key_exists( $fieldName, self::componentPaymentFields())
545285b8 232 ) {
d77aba4b
AS
233 $selectedPaymentFields = true;
234 $paymentTableId = 'participant_id';
545285b8 235 $returnProperties[$fieldName] = 1;
d77aba4b 236 }
6a488035
TO
237 else {
238 $returnProperties[$fieldName] = 1;
239
240 //campaign field export.
241 if (substr($fieldName, -8) == 'campaign') {
242 $fldNames = explode('_', $fieldName);
243 $returnProperties["{$fldNames[0]}_campaign_id"] = 1;
244 }
245 }
246 }
247 }
248
249 // hack to add default returnproperty based on export mode
250 if ($exportMode == CRM_Export_Form_Select::CONTRIBUTE_EXPORT) {
251 $returnProperties['contribution_id'] = 1;
252 }
253 elseif ($exportMode == CRM_Export_Form_Select::EVENT_EXPORT) {
254 $returnProperties['participant_id'] = 1;
255 if (CRM_Utils_Array::value('participant_role', $returnProperties)) {
256 unset($returnProperties['participant_role']);
257 $returnProperties['participant_role_id'] = 1;
258 }
259 }
260 elseif ($exportMode == CRM_Export_Form_Select::MEMBER_EXPORT) {
261 $returnProperties['membership_id'] = 1;
262 }
263 elseif ($exportMode == CRM_Export_Form_Select::PLEDGE_EXPORT) {
264 $returnProperties['pledge_id'] = 1;
265 }
266 elseif ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
267 $returnProperties['case_id'] = 1;
268 }
269 elseif ($exportMode == CRM_Export_Form_Select::GRANT_EXPORT) {
270 $returnProperties['grant_id'] = 1;
271 }
272 elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
273 $returnProperties['activity_id'] = 1;
274 }
275 }
276 else {
277 $primary = TRUE;
278 $fields = CRM_Contact_BAO_Contact::exportableFields('All', TRUE, TRUE);
279 foreach ($fields as $key => $var) {
280 if ($key && (substr($key, 0, 6) != 'custom')) {
281 //for CRM=952
282 $returnProperties[$key] = 1;
283 }
284 }
285
286 if ($primary) {
287 $returnProperties['location_type'] = 1;
288 $returnProperties['im_provider'] = 1;
289 $returnProperties['phone_type_id'] = 1;
290 $returnProperties['provider_id'] = 1;
291 $returnProperties['current_employer'] = 1;
292 }
293
294 $extraReturnProperties = array();
295 $paymentFields = FALSE;
296
297 switch ($queryMode) {
298 case CRM_Contact_BAO_Query::MODE_EVENT:
299 $paymentFields = TRUE;
300 $paymentTableId = 'participant_id';
301 break;
302
303 case CRM_Contact_BAO_Query::MODE_MEMBER:
304 $paymentFields = TRUE;
305 $paymentTableId = 'membership_id';
306 break;
307
308 case CRM_Contact_BAO_Query::MODE_PLEDGE:
309 $extraReturnProperties = CRM_Pledge_BAO_Query::extraReturnProperties($queryMode);
310 $paymentFields = TRUE;
311 $paymentTableId = 'pledge_payment_id';
312 break;
313
314 case CRM_Contact_BAO_Query::MODE_CASE:
315 $extraReturnProperties = CRM_Case_BAO_Query::extraReturnProperties($queryMode);
316 break;
317 }
318
319 if ($queryMode != CRM_Contact_BAO_Query::MODE_CONTACTS) {
320 $componentReturnProperties = CRM_Contact_BAO_Query::defaultReturnProperties($queryMode);
321
322 $campaignReturnProperties = array();;
323 foreach ($componentReturnProperties as $fld => $true) {
324 $campaignReturnProperties[$fld] = $true;
325 if (substr($fld, -11) == 'campaign_id') {
326 $exportCampaign = TRUE;
327 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
328 }
329 }
330 $componentReturnProperties = $campaignReturnProperties;
331
332 $returnProperties = array_merge($returnProperties, $componentReturnProperties);
333
334 if (!empty($extraReturnProperties)) {
335 $returnProperties = array_merge($returnProperties, $extraReturnProperties);
336 }
337
338 // unset non exportable fields for components
339 $nonExpoFields = array(
340 'groups', 'tags', 'notes', 'contribution_status_id',
341 'pledge_status_id', 'pledge_payment_status_id',
342 );
343 foreach ($nonExpoFields as $value) {
344 unset($returnProperties[$value]);
345 }
346 }
347 }
348
349 if ($mergeSameAddress) {
350 //make sure the addressee fields are selected
351 //while using merge same address feature
352 $returnProperties['addressee'] = 1;
353 $returnProperties['postal_greeting'] = 1;
354 $returnProperties['email_greeting'] = 1;
355 $returnProperties['street_name'] = 1;
356 $returnProperties['household_name'] = 1;
357 $returnProperties['street_address'] = 1;
358 $returnProperties['city'] = 1;
359 $returnProperties['state_province'] = 1;
360
361 // some columns are required for assistance incase they are not already present
362 $exportParams['merge_same_address']['temp_columns'] = array();
363 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
364 foreach ($tempColumns as $column) {
365 if (!array_key_exists($column, $returnProperties)) {
366 $returnProperties[$column] = 1;
367 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
368 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
369 }
370 }
371 }
372
34b773b7 373 if (!$selectAll && $componentTable && CRM_Utils_Array::value('additional_group', $exportParams)) {
6a488035
TO
374 // If an Additional Group is selected, then all contacts in that group are
375 // added to the export set (filtering out duplicates).
376 $query = "
377INSERT 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";
378 CRM_Core_DAO::executeQuery($query);
379 }
380
381 if ($moreReturnProperties) {
382 // fix for CRM-7066
383 if (CRM_Utils_Array::value('group', $moreReturnProperties)) {
384 unset($moreReturnProperties['group']);
385 $moreReturnProperties['groups'] = 1;
386 }
387 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
388 }
389
390 $exportParams['postal_mailing_export']['temp_columns'] = array();
391 if ($exportParams['exportOption'] == 2 &&
392 isset($exportParams['postal_mailing_export']) &&
393 CRM_Utils_Array::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
394 ) {
395 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
396 foreach ($postalColumns as $column) {
397 if (!array_key_exists($column, $returnProperties)) {
398 $returnProperties[$column] = 1;
399 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
400 }
401 }
402 }
403
fdb9cf51 404 $query = new CRM_Contact_BAO_Query($params, $returnProperties, NULL,
6a488035
TO
405 FALSE, FALSE, $queryMode,
406 FALSE, TRUE, TRUE, NULL, $queryOperator
407 );
408
409 list($select, $from, $where, $having) = $query->query();
410
411 if ($mergeSameHousehold == 1) {
412 if (!$returnProperties['id']) {
413 $returnProperties['id'] = 1;
414 }
415
416 //also merge Head of Household
417 $relationKeyMOH = CRM_Utils_Array::key('Household Member of', $contactRelationshipTypes);
418 $relationKeyHOH = CRM_Utils_Array::key('Head of Household for', $contactRelationshipTypes);
419
420 foreach ($returnProperties as $key => $value) {
421 if (!array_key_exists($key, $contactRelationshipTypes)) {
422 $returnProperties[$relationKeyMOH][$key] = $value;
423 $returnProperties[$relationKeyHOH][$key] = $value;
424 }
425 }
426
427 unset($returnProperties[$relationKeyMOH]['location_type']);
428 unset($returnProperties[$relationKeyMOH]['im_provider']);
429 unset($returnProperties[$relationKeyHOH]['location_type']);
430 unset($returnProperties[$relationKeyHOH]['im_provider']);
431 }
432
433 $allRelContactArray = $relationQuery = array();
434
435 foreach ($contactRelationshipTypes as $rel => $dnt) {
436 if ($relationReturnProperties = CRM_Utils_Array::value($rel, $returnProperties)) {
437 $allRelContactArray[$rel] = array();
438 // build Query for each relationship
439 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
440 NULL, FALSE, FALSE, $queryMode
441 );
442 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
443
444 list($id, $direction) = explode('_', $rel, 2);
445 // identify the relationship direction
446 $contactA = 'contact_id_a';
447 $contactB = 'contact_id_b';
448 if ($direction == 'b_a') {
449 $contactA = 'contact_id_b';
450 $contactB = 'contact_id_a';
451 }
452 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
453 $relIDs = $ids;
454 }
455 elseif ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
ad7695c2 456 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
b4eac1e9 457 $query = "SELECT contact_id FROM civicrm_activity_contact
458 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
459 record_type_id = {$sourceID}";
6a488035
TO
460 $dao = CRM_Core_DAO::executeQuery($query);
461 while ($dao->fetch()) {
b4eac1e9 462 $relIDs[] = $dao->contact_id;
6a488035
TO
463 }
464 }
465 else {
466 switch ($exportMode) {
467 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
468 $component = 'civicrm_contribution';
469 break;
470
471 case CRM_Export_Form_Select::EVENT_EXPORT:
472 $component = 'civicrm_participant';
473 break;
474
475 case CRM_Export_Form_Select::MEMBER_EXPORT:
476 $component = 'civicrm_membership';
477 break;
478
479 case CRM_Export_Form_Select::PLEDGE_EXPORT:
480 $component = 'civicrm_pledge';
481 break;
482
6a488035
TO
483 case CRM_Export_Form_Select::GRANT_EXPORT:
484 $component = 'civicrm_grant';
485 break;
486 }
040898fe 487
488 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
489 $relIDs = CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
490 }
491 else {
492 $relIDs = CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
493 }
6a488035
TO
494 }
495
496 $relationshipJoin = $relationshipClause = '';
34b773b7 497 if (!$selectAll && $componentTable) {
498 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
6a488035 499 }
34b773b7 500 elseif (!empty($relIDs)) {
6a488035
TO
501 $relID = implode(',', $relIDs);
502 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
503 }
504
505 $relationFrom = " {$relationFrom}
506 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
507 {$relationshipJoin} ";
508
509 //check for active relationship status only
510 $today = date('Ymd');
511 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
512 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
513 $relationGroupBy = " GROUP BY crel.{$contactA}";
514 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
515 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
516
517 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
518 while ($allRelContactDAO->fetch()) {
519 //FIX Me: Migrate this to table rather than array
520 // build the array of all related contacts
521 $allRelContactArray[$rel][$allRelContactDAO->refContact] = clone($allRelContactDAO);
522 }
523 $allRelContactDAO->free();
524 }
525 }
526
527 // make sure the groups stuff is included only if specifically specified
528 // by the fields param (CRM-1969), else we limit the contacts outputted to only
529 // ones that are part of a group
530 if (CRM_Utils_Array::value('groups', $returnProperties)) {
531 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
532 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
533 // total hack for export, CRM-3618
534 $from = str_replace($oldClause,
535 $newClause,
536 $from
537 );
538 }
539
34b773b7 540 if (!$selectAll && $componentTable) {
6a488035
TO
541 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
542 }
543 elseif ($componentClause) {
544 if (empty($where)) {
545 $where = "WHERE $componentClause";
546 }
547 else {
548 $where .= " AND $componentClause";
549 }
550 }
551
552 $queryString = "$select $from $where $having";
553
554 $groupBy = "";
555 if (CRM_Utils_Array::value('tags', $returnProperties) ||
556 CRM_Utils_Array::value('groups', $returnProperties) ||
557 CRM_Utils_Array::value('notes', $returnProperties) ||
558 // CRM-9552
559 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
560 ) {
561 $groupBy = " GROUP BY contact_a.id";
562 }
563
564 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
565 $groupBy = " GROUP BY civicrm_activity.id ";
566 }
567 $queryString .= $groupBy;
568 if ($order) {
569 list($field, $dir) = explode(' ', $order, 2);
570 $field = trim($field);
571 if (CRM_Utils_Array::value($field, $returnProperties)) {
572 // $queryString .= " ORDER BY $order";
573 }
574 }
575
576 $multipleSelectFields = array('preferred_communication_method' => 1);
577
578 $addPaymentHeader = FALSE;
579
580 $paymentDetails = array();
d77aba4b 581 if ($paymentFields || $selectedPaymentFields) {
6a488035
TO
582
583 // get payment related in for event and members
584 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
d77aba4b 585 //get all payment headers.
7460c131
AS
586 // If we haven't selected specific payment fields, load in all the
587 // payment headers.
d77aba4b
AS
588 if (!$selectedPaymentFields) {
589 $paymentHeaders = self::componentPaymentFields();
590 if (!empty($paymentDetails)) {
591 $addPaymentHeader = TRUE;
592 }
6a488035 593 }
7460c131
AS
594 // If we have seleted specific payment fields, leave the payment headers
595 // as an empty array; the headers for each selected field will be added
596 // elsewhere.
597 else {
598 $paymentHeaders = array();
599 }
6a488035
TO
600 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
601 }
602
603 //get all campaigns.
604 if ($exportCampaign) {
605 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
606 }
607
608 $componentDetails = $headerRows = $sqlColumns = array();
609 $setHeader = TRUE;
610
611 $rowCount = self::EXPORT_ROW_COUNT;
612 $offset = 0;
613 // we write to temp table often to avoid using too much memory
614 $tempRowCount = 100;
615
616 $count = -1;
617
618 // for CRM-3157 purposes
619 $i18n = CRM_Core_I18n::singleton();
620
621 while (1) {
622 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
623 $dao = CRM_Core_DAO::executeQuery($limitQuery);
624 if ($dao->N <= 0) {
625 break;
626 }
627
628 while ($dao->fetch()) {
629 $count++;
630 $row = array();
631
1571c7e7 632 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
633 //convert the pseudo constants
634 $query->convertToPseudoNames($dao);
635 }
d9ab802d 636
6a488035
TO
637 //first loop through returnproperties so that we return what is required, and in same order.
638 $relationshipField = 0;
639 foreach ($returnProperties as $field => $value) {
640 //we should set header only once
641 if ($setHeader) {
642 $sqlDone = FALSE;
643 if (isset($query->_fields[$field]['title'])) {
644 $headerRows[] = $query->_fields[$field]['title'];
645 }
646 elseif ($field == 'phone_type_id') {
647 $headerRows[] = ts('Phone Type');
648 }
649 elseif ($field == 'provider_id') {
650 $headerRows[] = ts('IM Service Provider');
651 }
652 elseif (is_array($value) && $field == 'location') {
653 // fix header for location type case
654 foreach ($value as $ltype => $val) {
655 foreach (array_keys($val) as $fld) {
656 $type = explode('-', $fld);
657 $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
658
659 if (CRM_Utils_Array::value(1, $type)) {
660 if (CRM_Utils_Array::value(0, $type) == 'phone') {
661 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
662 }
663 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
664 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
665 }
666 }
667 $headerRows[] = $hdr;
668 self::sqlColumnDefn($query, $sqlColumns, $hdr);
669 }
670 $sqlDone = TRUE;
671 }
672 }
673 elseif (substr($field, 0, 5) == 'case_') {
674 if ($query->_fields['case'][$field]['title']) {
675 $headerRows[] = $query->_fields['case'][$field]['title'];
676 }
677 elseif ($query->_fields['activity'][$field]['title']) {
678 $headerRows[] = $query->_fields['activity'][$field]['title'];
679 }
680 }
681 elseif (array_key_exists($field, $contactRelationshipTypes)) {
682 $relName = $field;
683 foreach ($value as $relationField => $relationValue) {
684 // below block is same as primary block (duplicate)
685 if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
686 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
687 $headerName = $field . '-' . $relationField;
688 }
689 else {
690 if ($relationField == 'current_employer') {
691 $headerName = $field . '-' . 'current_employer';
692 }
693 else {
694 $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
695 }
696 }
697
698 $headerRows[] = $headerName;
699
700 self::sqlColumnDefn($query, $sqlColumns, $headerName);
701 }
702 elseif ($relationField == 'phone_type_id') {
703 $headerName = $field . '-' . 'Phone Type';
704 $headerRows[] = $headerName;
705 self::sqlColumnDefn($query, $sqlColumns, $headerName);
706 }
707 elseif ($relationField == 'provider_id') {
708 $headerName = $field . '-' . 'Im Service Provider';
709 $headerRows[] = $headerName;
710 self::sqlColumnDefn($query, $sqlColumns, $headerName);
711 }
712 elseif ($relationField == 'state_province_id') {
713 $headerName = $field . '-' . 'state_province_id';
714 $headerRows[] = $headerName;
715 self::sqlColumnDefn($query, $sqlColumns, $headerName);
716 }
717 elseif (is_array($relationValue) && $relationField == 'location') {
718 // fix header for location type case
719 foreach ($relationValue as $ltype => $val) {
720 foreach (array_keys($val) as $fld) {
721 $type = explode('-', $fld);
722
723 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
724
725 if (CRM_Utils_Array::value(1, $type)) {
726 if (CRM_Utils_Array::value(0, $type) == 'phone') {
727 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
728 }
729 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
730 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
731 }
732 }
733 $headerName = $field . '-' . $hdr;
734 $headerRows[] = $headerName;
735 self::sqlColumnDefn($query, $sqlColumns, $headerName);
736 }
737 }
738 }
739 }
740 }
d77aba4b
AS
741 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
742 $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
743 }
6a488035
TO
744 else {
745 $headerRows[] = $field;
746 }
747
748 if (!$sqlDone) {
749 self::sqlColumnDefn($query, $sqlColumns, $field);
750 }
751 }
752
753 // add im_provider to $dao object
754 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
755 $dao->im_provider = $dao->provider_id;
756 }
757
758 //build row values (data)
759 $fieldValue = NULL;
760 if (property_exists($dao, $field)) {
761 $fieldValue = $dao->$field;
762 // to get phone type from phone type id
763 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
764 $fieldValue = $phoneTypes[$fieldValue];
765 }
766 elseif ($field == 'provider_id' || $field == 'im_provider') {
767 $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
768 }
769 elseif ($field == 'participant_role_id') {
770 $participantRoles = CRM_Event_PseudoConstant::participantRole();
771 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
772 $viewRoles = array();
773 foreach (explode($sep, $dao->$field) as $k => $v) {
774 $viewRoles[] = $participantRoles[$v];
775 }
776 $fieldValue = implode(',', $viewRoles);
777 }
778 elseif ($field == 'master_id') {
779 $masterAddressId = NULL;
780 if (isset($dao->master_id)) {
781 $masterAddressId = $dao->master_id;
782 }
783 // get display name of contact that address is shared.
784 $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $dao->contact_id);
785 }
786 }
787
788 if ($field == 'id') {
789 $row[$field] = $dao->contact_id;
790 // special case for calculated field
791 }
d4a280d8 792 elseif ($field == 'source_contact_id') {
793 $row[$field] = $dao->contact_id;
794 }
6a488035
TO
795 elseif ($field == 'pledge_balance_amount') {
796 $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
797 // special case for calculated field
798 }
799 elseif ($field == 'pledge_next_pay_amount') {
800 $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
801 }
a77049fb 802 elseif (in_array(substr($field, 0, -3), array('gender', 'prefix', 'suffix'))) {
803 $row[$field] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $field, $dao->$field);
d9ab802d 804 }
6a488035
TO
805 elseif (is_array($value) && $field == 'location') {
806 // fix header for location type case
807 foreach ($value as $ltype => $val) {
808 foreach (array_keys($val) as $fld) {
809 $type = explode('-', $fld);
810 $fldValue = "{$ltype}-" . $type[0];
811
812 if (CRM_Utils_Array::value(1, $type)) {
813 $fldValue .= "-" . $type[1];
814 }
815
816 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
817 switch ($fld) {
818 case 'country':
819 case 'world_region':
820 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'country'));
821 break;
822
823 case 'state_province':
824 $row[$fldValue] = $i18n->crm_translate($dao->$fldValue, array('context' => 'province'));
825 break;
826
827 case 'im_provider':
828 $imFieldvalue = $fldValue . "-provider_id";
829 $row[$fldValue] = CRM_Utils_Array::value($dao->$imFieldvalue, $imProviders);
830 break;
831
832 default:
833 $row[$fldValue] = $dao->$fldValue;
834 break;
835 }
836 }
837 }
838 }
839 elseif (array_key_exists($field, $contactRelationshipTypes)) {
840 $relDAO = CRM_Utils_Array::value($dao->contact_id, $allRelContactArray[$field]);
841 foreach ($value as $relationField => $relationValue) {
842 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
843 $fieldValue = $relDAO->$relationField;
844 if ($relationField == 'phone_type_id') {
845 $fieldValue = $phoneTypes[$relationValue];
846 }
847 elseif ($relationField == 'provider_id') {
848 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
849 }
850 }
851 else {
852 $fieldValue = '';
853 }
854 $field = $field . '_';
855 if (is_object($relDAO) && $relationField == 'id') {
856 $row[$field . $relationField] = $relDAO->contact_id;
857 } else if ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
858 foreach ($relationValue as $ltype => $val) {
859 foreach (array_keys($val) as $fld) {
860 $type = explode('-', $fld);
861 $fldValue = "{$ltype}-" . $type[0];
862 if (CRM_Utils_Array::value(1, $type)) {
863 $fldValue .= "-" . $type[1];
864 }
865 // CRM-3157: localise country, region (both have ‘country’ context)
866 // and state_province (‘province’ context)
867 switch (TRUE) {
868 case (!is_object($relDAO)):
869 $row[$field . '_' . $fldValue] = '';
870 break;
871
872 case in_array('country', $type):
873 case in_array('world_region', $type):
874 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
875 array('context' => 'country')
876 );
877 break;
878
879 case in_array('state_province', $type):
880 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
881 array('context' => 'province')
882 );
883 break;
884
885 default:
886 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
887 break;
888 }
889 }
890 }
891 }
892 elseif (isset($fieldValue) && $fieldValue != '') {
893 //check for custom data
894 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
895 $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID,
896 $relationQuery[$field]->_options
897 );
898 }
899 elseif (in_array($relationField, array(
900 'email_greeting', 'postal_greeting', 'addressee'))) {
901 //special case for greeting replacement
902 $fldValue = "{$relationField}_display";
903 $row[$field . $relationField] = $relDAO->$fldValue;
904 }
905 else {
906 //normal relationship fields
907 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
908 switch ($relationField) {
909 case 'country':
910 case 'world_region':
911 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
912 break;
913
914 case 'state_province':
915 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
916 break;
917
918 default:
919 $row[$field . $relationField] = $fieldValue;
920 break;
921 }
922 }
923 }
924 else {
925 // if relation field is empty or null
926 $row[$field . $relationField] = '';
927 }
928 }
929 }
930 elseif (isset($fieldValue) &&
931 $fieldValue != ''
932 ) {
933 //check for custom data
934 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
935 $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
936 }
937 elseif (array_key_exists($field, $multipleSelectFields)) {
938 //option group fixes
939 $paramsNew = array($field => $fieldValue);
940 if ($field == 'test_tutoring') {
941 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
942 // for readers group
943 }
944 elseif (substr($field, 0, 4) == 'cmr_') {
945 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
946 }
947 else {
948 $name = array($field => array('newName' => $field, 'groupName' => $field));
949 }
950 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
951 $row[$field] = $paramsNew[$field];
952 }
953 elseif (in_array($field, array(
954 'email_greeting', 'postal_greeting', 'addressee'))) {
955 //special case for greeting replacement
956 $fldValue = "{$field}_display";
957 $row[$field] = $dao->$fldValue;
958 }
959 else {
960 //normal fields with a touch of CRM-3157
961 switch ($field) {
962 case 'country':
963 case 'world_region':
964 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
965 break;
966
967 case 'state_province':
968 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
969 break;
970
971 case 'gender':
972 case 'preferred_communication_method':
973 case 'preferred_mail_format':
974 $row[$field] = $i18n->crm_translate($fieldValue);
975 break;
976
977 default:
978 $row[$field] = $fieldValue;
979 break;
980 }
981 }
982 }
983 elseif (substr($field, -8) == 'campaign') {
984 $campIdFld = "{$field}_id";
985 $row[$field] = CRM_Utils_Array::value($dao->$campIdFld, $allCampaigns, '');
986 }
d77aba4b
AS
987 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
988 $paymentData = CRM_Utils_Array::value($dao->$paymentTableId, $paymentDetails);
989 $payFieldMapper = array(
990 'componentPaymentField_total_amount' => 'total_amount',
991 'componentPaymentField_contribution_status' => 'contribution_status',
992 'componentPaymentField_payment_instrument' => 'pay_instru',
993 'componentPaymentField_transaction_id' => 'trxn_id',
994 'componentPaymentField_received_date' => 'receive_date',
995 );
996 $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
997 }
6a488035
TO
998 else {
999 // if field is empty or null
1000 $row[$field] = '';
1001 }
1002 }
1003
1004 // add payment headers if required
1005 if ($addPaymentHeader && $paymentFields) {
1006 $headerRows = array_merge($headerRows, $paymentHeaders);
1007 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1008 self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1009 }
6a488035
TO
1010 }
1011
1012 if ($setHeader) {
1013 $exportTempTable = self::createTempTable($sqlColumns);
1014 }
1015
1016 //build header only once
1017 $setHeader = FALSE;
1018
e026db3c 1019 // If specific payment fields have been selected for export, payment
545285b8 1020 // data will already be in $row. Otherwise, add payment related
e026db3c 1021 // information, if appropriate.
fc33177b 1022 if ($addPaymentHeader) {
1023 if (!$selectedPaymentFields) {
1024 if ($paymentFields) {
1025 $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
1026 if (!is_array($paymentData) || empty($paymentData)) {
1027 $paymentData = $nullContributionDetails;
1028 }
1029 $row = array_merge($row, $paymentData);
1030 }
1031 elseif (!empty($paymentDetails)) {
1032 $row = array_merge($row, $nullContributionDetails);
e026db3c 1033 }
e026db3c 1034 }
6a488035 1035 }
6a488035
TO
1036 //remove organization name for individuals if it is set for current employer
1037 if (CRM_Utils_Array::value('contact_type', $row) &&
1038 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1039 ) {
1040 $row['organization_name'] = '';
1041 }
1042
1043 // add component info
1044 // write the row to a file
1045 $componentDetails[] = $row;
1046
1047 // output every $tempRowCount rows
1048 if ($count % $tempRowCount == 0) {
1049 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1050 $componentDetails = array();
1051 }
1052 }
1053 $dao->free();
1054 $offset += $rowCount;
1055 }
1056
1057 if ($exportTempTable) {
1058 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1059
1060 // do merge same address and merge same household processing
1061 if ($mergeSameAddress) {
1062 self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1063 }
1064
1065 // merge the records if they have corresponding households
1066 if ($mergeSameHousehold) {
1067 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1068 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1069 }
1070
1071 // fix the headers for rows with relationship type
1072 if (!empty($relName)) {
1073 self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1074 }
1075
1076 // if postalMailing option is checked, exclude contacts who are deceased, have
1077 // "Do not mail" privacy setting, or have no street address
1078 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1079 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1080 ) {
1081 self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1082 }
1083
1084 // call export hook
1085 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1086
1087 // now write the CSV file
1088 self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1089
1090 // delete the export temp table and component table
1091 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1092 CRM_Core_DAO::executeQuery($sql);
1093
1094 CRM_Utils_System::civiExit();
1095 }
1096 else {
1097 CRM_Core_Error::fatal(ts('No records to export'));
1098 }
1099 }
1100
1101 /**
1102 * name of the export file based on mode
1103 *
1104 * @param string $output type of output
1105 * @param int $mode export mode
1106 *
1107 * @return string name of the file
1108 */
25acfd6b 1109 static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select::CONTACT_EXPORT) {
6a488035
TO
1110 switch ($mode) {
1111 case CRM_Export_Form_Select::CONTACT_EXPORT:
1112 return ts('CiviCRM Contact Search');
1113
1114 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
1115 return ts('CiviCRM Contribution Search');
1116
1117 case CRM_Export_Form_Select::MEMBER_EXPORT:
1118 return ts('CiviCRM Member Search');
1119
1120 case CRM_Export_Form_Select::EVENT_EXPORT:
1121 return ts('CiviCRM Participant Search');
1122
1123 case CRM_Export_Form_Select::PLEDGE_EXPORT:
1124 return ts('CiviCRM Pledge Search');
1125
1126 case CRM_Export_Form_Select::CASE_EXPORT:
1127 return ts('CiviCRM Case Search');
1128
1129 case CRM_Export_Form_Select::GRANT_EXPORT:
1130 return ts('CiviCRM Grant Search');
1131
1132 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
1133 return ts('CiviCRM Activity Search');
1134 }
1135 }
1136
1137 /**
1138 * Function to handle import error file creation.
1139 *
1140 */
1141 function invoke() {
1142 $type = CRM_Utils_Request::retrieve('type', 'Positive', CRM_Core_DAO::$_nullObject);
1143 $parserName = CRM_Utils_Request::retrieve('parser', 'String', CRM_Core_DAO::$_nullObject);
1144 if (empty($parserName) || empty($type)) {
1145 return;
1146 }
1147
1148 // clean and ensure parserName is a valid string
1149 $parserName = CRM_Utils_String::munge($parserName);
1150 $parserClass = explode('_', $parserName);
1151
1152 // make sure parserClass is in the CRM namespace and
1153 // at least 3 levels deep
1154 if ($parserClass[0] == 'CRM' &&
1155 count($parserClass) >= 3
1156 ) {
1157 require_once (str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php");
1158 // ensure the functions exists
1159 if (method_exists($parserName, 'errorFileName') &&
1160 method_exists($parserName, 'saveFileName')
1161 ) {
1162 $errorFileName = $parserName::errorFileName($type);
1163 $saveFileName = $parserName::saveFileName($type);
1164 if (!empty($errorFileName) && !empty($saveFileName)) {
1165 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1166 header('Content-Description: File Transfer');
1167 header('Content-Type: text/csv');
1168 header('Content-Length: ' . filesize($errorFileName));
1169 header('Content-Disposition: attachment; filename=' . $saveFileName);
1170
1171 readfile($errorFileName);
1172 }
1173 }
1174 }
1175 CRM_Utils_System::civiExit();
1176 }
1177
1178 function exportCustom($customSearchClass, $formValues, $order) {
1179 $ext = CRM_Extension_System::singleton()->getMapper();
1180 if (!$ext->isExtensionClass($customSearchClass)) {
1181 require_once (str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php');
1182 }
1183 else {
1184 require_once ($ext->classToPath($customSearchClass));
1185 }
1186 $search = new $customSearchClass($formValues);
1187
1188 $includeContactIDs = FALSE;
1189 if ($formValues['radio_ts'] == 'ts_sel') {
1190 $includeContactIDs = TRUE;
1191 }
1192
1193 $sql = $search->all(0, 0, $order, $includeContactIDs);
1194
1195 $columns = $search->columns();
1196
1197 $header = array_keys($columns);
1198 $fields = array_values($columns);
1199
1200 $rows = array();
1201 $dao = CRM_Core_DAO::executeQuery($sql);
1202 $alterRow = FALSE;
1203 if (method_exists($search, 'alterRow')) {
1204 $alterRow = TRUE;
1205 }
1206 while ($dao->fetch()) {
1207 $row = array();
1208
1209 foreach ($fields as $field) {
1210 $row[$field] = $dao->$field;
1211 }
1212 if ($alterRow) {
1213 $search->alterRow($row);
1214 }
1215 $rows[] = $row;
1216 }
1217
1218 CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName(), $header, $rows);
1219 CRM_Utils_System::civiExit();
1220 }
1221
1222 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
0944820d 1223 if (substr($field, -4) == '_a_b' || substr($field, -4) == '_b_a') {
6a488035
TO
1224 return;
1225 }
1226
1227 $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
1228 if ($fieldName == 'id') {
1229 $fieldName = 'civicrm_primary_id';
1230 }
1231
0944820d
DL
1232 // early exit for master_id, CRM-12100
1233 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1234 if ($fieldName == 'master_id') {
1235 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1236 return;
1237 }
1238
6a488035
TO
1239 // set the sql columns
1240 if (isset($query->_fields[$field]['type'])) {
1241 switch ($query->_fields[$field]['type']) {
1242 case CRM_Utils_Type::T_INT:
6a488035
TO
1243 case CRM_Utils_Type::T_BOOLEAN:
1244 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1245 break;
1246
1247 case CRM_Utils_Type::T_STRING:
1248 if (isset($query->_fields[$field]['maxlength'])) {
1249 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1250 }
1251 else {
1252 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1253 }
1254 break;
1255
1256 case CRM_Utils_Type::T_TEXT:
1257 case CRM_Utils_Type::T_LONGTEXT:
1258 case CRM_Utils_Type::T_BLOB:
1259 case CRM_Utils_Type::T_MEDIUMBLOB:
1260 $sqlColumns[$fieldName] = "$fieldName longtext";
1261 break;
1262
1263 case CRM_Utils_Type::T_FLOAT:
1264 case CRM_Utils_Type::T_ENUM:
1265 case CRM_Utils_Type::T_DATE:
1266 case CRM_Utils_Type::T_TIME:
1267 case CRM_Utils_Type::T_TIMESTAMP:
1268 case CRM_Utils_Type::T_MONEY:
1269 case CRM_Utils_Type::T_EMAIL:
1270 case CRM_Utils_Type::T_URL:
1271 case CRM_Utils_Type::T_CCNUM:
1272 default:
1273 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1274 break;
1275 }
1276 }
1277 else {
1278 if (substr($fieldName, -3, 3) == '_id') {
1279 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1280 }
1281 else {
1282 $changeFields = array(
1283 'groups',
1284 'tags',
1285 'notes'
1286 );
1287
1288 if (in_array($fieldName, $changeFields)) {
1289 $sqlColumns[$fieldName] = "$fieldName text";
1290 }
1291 else {
1292 // set the sql columns for custom data
1293 if (isset($query->_fields[$field]['data_type'])) {
1294
1295 switch ($query->_fields[$field]['data_type']) {
1296 case 'Country':
1297 case 'StateProvince':
1298 case 'Link':
1299 case 'String':
1300 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1301 break;
1302
1303 case 'Memo':
1304 $sqlColumns[$fieldName] = "$fieldName text";
1305 break;
1306
1307 default:
1308 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1309 break;
1310 }
1311 }
1312 else {
1313 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1314 }
1315 }
1316 }
1317 }
1318 }
1319
1320 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1321 if (empty($details)) {
1322 return;
1323 }
1324
1325 $sql = "
1326SELECT max(id)
1327FROM $tableName
1328";
1329
1330 $id = CRM_Core_DAO::singleValueQuery($sql);
1331 if (!$id) {
1332 $id = 0;
1333 }
1334
1335 $sqlClause = array();
1336
1337 foreach ($details as $dontCare => $row) {
1338 $id++;
1339 $valueString = array($id);
1340 foreach ($row as $dontCare => $value) {
1341 if (empty($value)) {
1342 $valueString[] = "''";
1343 }
1344 else {
1345 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
1346 }
1347 }
1348 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1349 }
1350
1351 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1352
1353 $sqlValueString = implode(",\n", $sqlClause);
1354
1355 $sql = "
1356INSERT INTO $tableName $sqlColumnString
1357VALUES $sqlValueString
1358";
1359
1360 CRM_Core_DAO::executeQuery($sql);
1361 }
1362
1363 static function createTempTable(&$sqlColumns) {
1364 //creating a temporary table for the search result that need be exported
1365 $exportTempTable = CRM_Core_DAO::createTempTableName('civicrm_export', TRUE);
1366
1367 // also create the sql table
1368 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1369 CRM_Core_DAO::executeQuery($sql);
1370
1371 $sql = "
1372CREATE TABLE {$exportTempTable} (
1373 id int unsigned NOT NULL AUTO_INCREMENT,
1374";
1375 $sql .= implode(",\n", array_values($sqlColumns));
1376
1377 $sql .= ",
1378 PRIMARY KEY ( id )
1379";
1380 // add indexes for street_address and household_name if present
1381 $addIndices = array(
1382 'street_address',
1383 'household_name',
1384 'civicrm_primary_id',
1385 );
1386
1387 foreach ($addIndices as $index) {
1388 if (isset($sqlColumns[$index])) {
1389 $sql .= ",
1390 INDEX index_{$index}( $index )
1391";
1392 }
1393 }
1394
1395 $sql .= "
1396) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1397";
1398
1399 CRM_Core_DAO::executeQuery($sql);
1400 return $exportTempTable;
1401 }
1402
1403 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1404 // check if any records are present based on if they have used shared address feature,
1405 // and not based on if city / state .. matches.
1406 $sql = "
1407SELECT r1.id as copy_id,
1408 r1.civicrm_primary_id as copy_contact_id,
1409 r1.addressee as copy_addressee,
1410 r1.addressee_id as copy_addressee_id,
1411 r1.postal_greeting as copy_postal_greeting,
1412 r1.postal_greeting_id as copy_postal_greeting_id,
1413 r2.id as master_id,
1414 r2.civicrm_primary_id as master_contact_id,
1415 r2.postal_greeting as master_postal_greeting,
1416 r2.postal_greeting_id as master_postal_greeting_id,
1417 r2.addressee as master_addressee,
1418 r2.addressee_id as master_addressee_id
1419FROM $tableName r1
1420INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1421INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1422ORDER BY r1.id";
1423 $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE);
1424
1425 // find all the records that have the same street address BUT not in a household
1426 // require match on city and state as well
1427 $sql = "
1428SELECT r1.id as master_id,
1429 r1.civicrm_primary_id as master_contact_id,
1430 r1.postal_greeting as master_postal_greeting,
1431 r1.postal_greeting_id as master_postal_greeting_id,
1432 r1.addressee as master_addressee,
1433 r1.addressee_id as master_addressee_id,
1434 r2.id as copy_id,
1435 r2.civicrm_primary_id as copy_contact_id,
1436 r2.postal_greeting as copy_postal_greeting,
1437 r2.postal_greeting_id as copy_postal_greeting_id,
1438 r2.addressee as copy_addressee,
1439 r2.addressee_id as copy_addressee_id
1440FROM $tableName r1
1441LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1442 r1.city = r2.city AND
1443 r1.state_province_id = r2.state_province_id )
1444WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1445AND ( r2.household_name IS NULL OR r2.household_name = '' )
1446AND ( r1.street_address != '' )
1447AND r2.id > r1.id
1448ORDER BY r1.id
1449";
1450 $merge = self::_buildMasterCopyArray($sql, $exportParams);
1451
1452 // unset ids from $merge already present in $linkedMerge
1453 foreach ($linkedMerge as $masterID => $values) {
1454 $keys = array($masterID);
1455 $keys = array_merge($keys, array_keys($values['copy']));
1456 foreach ($merge as $mid => $vals) {
1457 if (in_array($mid, $keys)) {
1458 unset($merge[$mid]);
1459 }
1460 else {
1461 foreach ($values['copy'] as $copyId) {
1462 if (in_array($copyId, $keys)) {
1463 unset($merge[$mid]['copy'][$copyId]);
1464 }
1465 }
1466 }
1467 }
1468 }
1469 $merge = $merge + $linkedMerge;
1470
1471 foreach ($merge as $masterID => $values) {
1472 $sql = "
1473UPDATE $tableName
1474SET addressee = %1, postal_greeting = %2, email_greeting = %3
1475WHERE id = %4
1476";
1477 $params = array(1 => array($values['addressee'], 'String'),
1478 2 => array($values['postalGreeting'], 'String'),
1479 3 => array($values['emailGreeting'], 'String'),
1480 4 => array($masterID, 'Integer'),
1481 );
1482 CRM_Core_DAO::executeQuery($sql, $params);
1483
1484 // delete all copies
1485 $deleteIDs = array_keys($values['copy']);
1486 $deleteIDString = implode(',', $deleteIDs);
1487 $sql = "
1488DELETE FROM $tableName
1489WHERE id IN ( $deleteIDString )
1490";
1491 CRM_Core_DAO::executeQuery($sql);
1492 }
1493
1494 // unset temporary columns that were added for postal mailing format
1495 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1496 $unsetKeys = array_keys($sqlColumns);
1497 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1498 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1499 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1500 }
1501 }
1502 }
1503 }
1504
1505 static function _replaceMergeTokens($contactId, $exportParams) {
1506 $greetings = array();
1507 $contact = NULL;
1508
1509 $greetingFields = array(
1510 'postal_greeting',
1511 'addressee',
1512 );
1513 foreach ($greetingFields as $greeting) {
1514 if (CRM_Utils_Array::value($greeting, $exportParams)) {
1515 $greetingLabel = $exportParams[$greeting];
1516 if (empty($contact)) {
1517 $values = array(
1518 'id' => $contactId,
1519 'version' => 3,
1520 );
1521 $contact = civicrm_api('contact', 'get', $values);
1522
1523 if (CRM_Utils_Array::value('is_error', $contact)) {
1524 return $greetings;
1525 }
1526 $contact = $contact['values'][$contact['id']];
1527 }
1528
1529 $tokens = array('contact' => $greetingLabel);
1530 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1531 }
1532 }
1533 return $greetings;
1534 }
1535
1536 /**
1537 * The function unsets static part of the string, if token is the dynamic part.
1538 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1539 * i.e 'Hello Alan' => converted to => 'Alan'
1540 *
1541 */
1542 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1543 $addressMergeGreetings, $greetingType = 'postal_greeting'
1544 ) {
1545 if (CRM_Utils_Array::value($greetingType, $addressMergeGreetings)) {
1546 $greetingLabel = $addressMergeGreetings[$greetingType];
1547 }
1548 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
1549
1550 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1551 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1552 foreach ($stringsToBeReplaced as $key => $string) {
1553 // to keep one space
1554 $stringsToBeReplaced[$key] = ltrim($string);
1555 }
1556 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1557
1558 return $parsedString;
1559 }
1560
1561 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1562 static $contactGreetingTokens = array();
1563
1564 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
1565 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
1566
1567 $merge = $parents = array();
1568 $dao = CRM_Core_DAO::executeQuery($sql);
1569
1570 while ($dao->fetch()) {
1571 $masterID = $dao->master_id;
1572 $copyID = $dao->copy_id;
1573 $masterPostalGreeting = $dao->master_postal_greeting;
1574 $masterAddressee = $dao->master_addressee;
1575 $copyAddressee = $dao->copy_addressee;
1576
1577 if (!$sharedAddress) {
1578 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
1579 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
1580 }
1581 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1582 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
1583 );
1584 $masterAddressee = CRM_Utils_Array::value('addressee',
1585 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
1586 );
1587
1588 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
1589 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
1590 }
1591 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1592 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
1593 );
1594 $copyAddressee = CRM_Utils_Array::value('addressee',
1595 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
1596 );
1597 }
1598
1599 if (!isset($merge[$masterID])) {
1600 // check if this is an intermediate child
1601 // this happens if there are 3 or more matches a,b, c
1602 // the above query will return a, b / a, c / b, c
1603 // we might be doing a bit more work, but for now its ok, unless someone
1604 // knows how to fix the query above
1605 if (isset($parents[$masterID])) {
1606 $masterID = $parents[$masterID];
1607 }
1608 else {
1609 $merge[$masterID] = array(
1610 'addressee' => $masterAddressee,
1611 'copy' => array(),
1612 'postalGreeting' => $masterPostalGreeting,
1613 );
1614 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1615 }
1616 }
1617 $parents[$copyID] = $masterID;
1618
1619 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1620
1621 if (CRM_Utils_Array::value('postal_greeting_other', $exportParams) &&
1622 count($merge[$masterID]['copy']) >= 1
1623 ) {
1624 // use static greetings specified if no of contacts > 2
1625 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1626 }
1627 elseif ($copyPostalGreeting) {
1628 self::_trimNonTokens($copyPostalGreeting,
1629 $postalOptions[$dao->copy_postal_greeting_id],
1630 $exportParams
1631 );
1632 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1633 // if there happens to be a duplicate, remove it
1634 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1635 }
1636
1637 if (CRM_Utils_Array::value('addressee_other', $exportParams) &&
1638 count($merge[$masterID]['copy']) >= 1
1639 ) {
1640 // use static greetings specified if no of contacts > 2
1641 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1642 }
1643 elseif ($copyAddressee) {
1644 self::_trimNonTokens($copyAddressee,
1645 $addresseeOptions[$dao->copy_addressee_id],
1646 $exportParams, 'addressee'
1647 );
1648 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1649 }
1650 }
1651 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1652 }
1653
1654 return $merge;
1655 }
1656
1657 /**
1658 * Function to merge household record into the individual record
1659 * if exists
1660 *
1661 * @param string $exportTempTable temporary temp table that stores the records
1662 * @param array $headerRows array of headers for the export file
1663 * @param array $sqlColumns array of names of the table columns of the temp table
1664 * @param string $prefix name of the relationship type that is prefixed to the table columns
1665 */
1666 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1667 $prefixColumn = $prefix . '_';
1668 $allKeys = array_keys($sqlColumns);
1669 $replaced = array();
1670 $headerRows = array_values($headerRows);
1671
1672 // name map of the non standard fields in header rows & sql columns
1673 $mappingFields = array(
1674 'civicrm_primary_id' => 'id',
1675 'contact_source' => 'source',
1676 'current_employer_id' => 'employer_id',
1677 'contact_is_deleted' => 'is_deleted',
1678 'name' => 'address_name',
1679 'provider_id' => 'im_service_provider',
1680 'phone_type_id' => 'phone_type'
1681 );
1682
1683 //figure out which columns are to be replaced by which ones
1684 foreach ($sqlColumns as $columnNames => $dontCare) {
1685 if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) {
1686 $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64);
1687 }
1688 else {
1689 $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64);
1690
1691 if (CRM_Utils_Array::value($householdColName, $sqlColumns)) {
1692 $replaced[$columnNames] = $householdColName;
1693 }
1694 }
1695 }
1696 $query = "UPDATE $exportTempTable SET ";
1697
1698 $clause = array();
1699 foreach ($replaced as $from => $to) {
1700 $clause[] = "$from = $to ";
1701 unset($sqlColumns[$to]);
1702 if ($key = CRM_Utils_Array::key($to, $allKeys)) {
1703 unset($headerRows[$key]);
1704 }
1705 }
1706 $query .= implode(",\n", $clause);
1707 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1708
1709 CRM_Core_DAO::executeQuery($query);
1710
1711 //drop the table columns that store redundant household info
1712 $dropQuery = "ALTER TABLE $exportTempTable ";
1713 foreach ($replaced as $householdColumns) {
1714 $dropClause[] = " DROP $householdColumns ";
1715 }
1716 $dropQuery .= implode(",\n", $dropClause);
1717
1718 CRM_Core_DAO::executeQuery($dropQuery);
1719
1720 // also drop the temp table if exists
1721 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1722 CRM_Core_DAO::executeQuery($sql);
1723
1724 // clean up duplicate records
1725 $query = "
1726CREATE TABLE {$exportTempTable}_temp SELECT *
1727FROM {$exportTempTable}
1728GROUP BY civicrm_primary_id ";
1729
1730 CRM_Core_DAO::executeQuery($query);
1731
1732 $query = "DROP TABLE $exportTempTable";
1733 CRM_Core_DAO::executeQuery($query);
1734
1735 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1736 CRM_Core_DAO::executeQuery($query);
1737 }
1738
1739 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1740 $writeHeader = TRUE;
1741 $offset = 0;
1742 $limit = self::EXPORT_ROW_COUNT;
1743
1744 $query = "SELECT * FROM $exportTempTable";
1745
1746 while (1) {
1747 $limitQuery = $query . "
1748LIMIT $offset, $limit
1749";
1750 $dao = CRM_Core_DAO::executeQuery($limitQuery);
1751
1752 if ($dao->N <= 0) {
1753 break;
1754 }
1755
1756 $componentDetails = array();
1757 while ($dao->fetch()) {
1758 $row = array();
1759
1760 foreach ($sqlColumns as $column => $dontCare) {
1761 $row[$column] = $dao->$column;
1762 }
1763 $componentDetails[] = $row;
1764 }
1765 if ( $exportMode == 'financial' ) {
1766 $getExportFileName = 'CiviCRM Contribution Search';
1767 }
1768 else {
1769 $getExportFileName =self::getExportFileName( 'csv', $exportMode );
1770 }
1771 $csvRows = CRM_Core_Report_Excel::writeCSVFile( $getExportFileName,
1772 $headerRows,
1773 $componentDetails,
1774 null,
1775 $writeHeader,
1776 $saveFile );
1777
1778 if ($saveFile && !empty($csvRows)) {
1779 $batchItems .= $csvRows;
1780 }
1781
1782 $writeHeader = false;
1783 $offset += $limit;
1784 }
1785 }
1786
1787 /**
1788 * Function to manipulate header rows for relationship fields
1789 *
1790 */
1571c7e7 1791 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
6a488035
TO
1792 foreach ($headerRows as & $header) {
1793 $split = explode('-', $header);
1794 if ($relationTypeName = CRM_Utils_Array::value($split[0], $contactRelationshipTypes)) {
1795 $split[0] = $relationTypeName;
1796 $header = implode('-', $split);
1797 }
1798 }
1799 }
1800
1801 /**
1802 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1803 * or have no street address
1804 *
1805 */
1806 function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1807 $whereClause = array();
1808
1809 if (array_key_exists('is_deceased', $sqlColumns)) {
1810 $whereClause[] = 'is_deceased = 1';
1811 }
1812
1813 if (array_key_exists('do_not_mail', $sqlColumns)) {
1814 $whereClause[] = 'do_not_mail = 1';
1815 }
1816
1817 if (array_key_exists('street_address', $sqlColumns)) {
1818 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1819
1820 // check for supplemental_address_1
1821 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1822 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1823 'address_options', TRUE, NULL, TRUE
1824 );
1825 if (CRM_Utils_Array::value('supplemental_address_1', $addressOptions)) {
1826 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1827 // enclose it again, since we are doing an AND in between a set of ORs
1828 $addressWhereClause = "( $addressWhereClause )";
1829 }
1830 }
1831
1832 $whereClause[] = $addressWhereClause;
1833 }
1834
1835 if (!empty($whereClause)) {
1836 $whereClause = implode(' OR ', $whereClause);
1837 $query = "
1838DELETE
1839FROM $exportTempTable
1840WHERE {$whereClause}";
1841 CRM_Core_DAO::singleValueQuery($query);
1842 }
1843
1844 // unset temporary columns that were added for postal mailing format
1845 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1846 $unsetKeys = array_keys($sqlColumns);
1847 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1848 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1849 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1850 }
1851 }
1852 }
1853 }
d77aba4b
AS
1854
1855 /**
1856 * Build componentPayment fields.
1857 */
1858 static function componentPaymentFields() {
1859 static $componentPaymentFields;
1860 if (!isset( $componentPaymentFields)) {
1861 $componentPaymentFields = array(
1862 'componentPaymentField_total_amount' => ts('Total Amount'),
1863 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1864 'componentPaymentField_received_date' => ts('Received Date'),
1865 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1866 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1867 );
1868 }
1869 return $componentPaymentFields;
1870 }
6a488035
TO
1871}
1872