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