Merge pull request #3294 from systopia/Ticket-#918
[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)) {
161 if (CRM_Utils_Array::value(2, $value)) {
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 }
177 elseif (CRM_Utils_Array::value(4, $value)) {
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;
245 if (CRM_Utils_Array::value('participant_role', $returnProperties)) {
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
34b773b7 352 if (!$selectAll && $componentTable && CRM_Utils_Array::value('additional_group', $exportParams)) {
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
362 if (CRM_Utils_Array::value('group', $moreReturnProperties)) {
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
509 if (CRM_Utils_Array::value('groups', $returnProperties)) {
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 = "";
548 if (CRM_Utils_Array::value('tags', $returnProperties) ||
549 CRM_Utils_Array::value('groups', $returnProperties) ||
550 CRM_Utils_Array::value('notes', $returnProperties) ||
551 // CRM-9552
552 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
553 ) {
554 $groupBy = " GROUP BY contact_a.id";
555 }
556
8a13a745 557 switch ($exportMode) {
558 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
559 $groupBy = 'GROUP BY civicrm_contribution.id';
560 break;
561
562 case CRM_Export_Form_Select::EVENT_EXPORT:
563 $groupBy = 'GROUP BY civicrm_participant.id';
564 break;
565
566 case CRM_Export_Form_Select::MEMBER_EXPORT:
567 $groupBy = " GROUP BY civicrm_membership.id";
568 break;
569 }
570
6a488035
TO
571 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
572 $groupBy = " GROUP BY civicrm_activity.id ";
573 }
574 $queryString .= $groupBy;
575 if ($order) {
576 list($field, $dir) = explode(' ', $order, 2);
577 $field = trim($field);
578 if (CRM_Utils_Array::value($field, $returnProperties)) {
579 // $queryString .= " ORDER BY $order";
580 }
581 }
582
583 $multipleSelectFields = array('preferred_communication_method' => 1);
584
585 $addPaymentHeader = FALSE;
586
587 $paymentDetails = array();
d77aba4b 588 if ($paymentFields || $selectedPaymentFields) {
6a488035
TO
589
590 // get payment related in for event and members
591 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
d77aba4b 592 //get all payment headers.
7460c131
AS
593 // If we haven't selected specific payment fields, load in all the
594 // payment headers.
d77aba4b
AS
595 if (!$selectedPaymentFields) {
596 $paymentHeaders = self::componentPaymentFields();
597 if (!empty($paymentDetails)) {
598 $addPaymentHeader = TRUE;
599 }
6a488035 600 }
7460c131
AS
601 // If we have seleted specific payment fields, leave the payment headers
602 // as an empty array; the headers for each selected field will be added
603 // elsewhere.
604 else {
605 $paymentHeaders = array();
606 }
6a488035
TO
607 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
608 }
609
93c29fb5
CW
610 // Split campaign into 2 fields for id and title
611 $campaignReturnProperties = array();
612 foreach ($returnProperties as $fld => $true) {
613 $campaignReturnProperties[$fld] = $true;
614 if (substr($fld, -11) == 'campaign_id') {
615 $exportCampaign = TRUE;
616 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
617 }
618 }
619 $returnProperties = $campaignReturnProperties;
6a488035 620 //get all campaigns.
93c29fb5 621 if (isset($exportCampaign)) {
6a488035
TO
622 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
623 }
624
625 $componentDetails = $headerRows = $sqlColumns = array();
626 $setHeader = TRUE;
627
628 $rowCount = self::EXPORT_ROW_COUNT;
629 $offset = 0;
630 // we write to temp table often to avoid using too much memory
631 $tempRowCount = 100;
632
633 $count = -1;
634
635 // for CRM-3157 purposes
636 $i18n = CRM_Core_I18n::singleton();
637
638 while (1) {
639 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
640 $dao = CRM_Core_DAO::executeQuery($limitQuery);
641 if ($dao->N <= 0) {
642 break;
643 }
644
645 while ($dao->fetch()) {
646 $count++;
647 $row = array();
648
b23943b8 649 //convert the pseudo constants
650 $query->convertToPseudoNames($dao);
d9ab802d 651
6a488035
TO
652 //first loop through returnproperties so that we return what is required, and in same order.
653 $relationshipField = 0;
654 foreach ($returnProperties as $field => $value) {
655 //we should set header only once
656 if ($setHeader) {
657 $sqlDone = FALSE;
93c29fb5
CW
658 // Split campaign into 2 fields for id and title
659 if (substr($field, -8) == 'campaign') {
660 $headerRows[] = ts('Campaign Title');
661 }
662 elseif (substr($field, -11) == 'campaign_id') {
663 $headerRows[] = ts('Campaign ID');
664 }
665 elseif (isset($query->_fields[$field]['title'])) {
6a488035
TO
666 $headerRows[] = $query->_fields[$field]['title'];
667 }
668 elseif ($field == 'phone_type_id') {
669 $headerRows[] = ts('Phone Type');
670 }
671 elseif ($field == 'provider_id') {
672 $headerRows[] = ts('IM Service Provider');
673 }
674 elseif (is_array($value) && $field == 'location') {
675 // fix header for location type case
676 foreach ($value as $ltype => $val) {
677 foreach (array_keys($val) as $fld) {
678 $type = explode('-', $fld);
679 $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
680
681 if (CRM_Utils_Array::value(1, $type)) {
682 if (CRM_Utils_Array::value(0, $type) == 'phone') {
683 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
684 }
685 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
686 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
687 }
688 }
689 $headerRows[] = $hdr;
690 self::sqlColumnDefn($query, $sqlColumns, $hdr);
691 }
692 $sqlDone = TRUE;
693 }
694 }
695 elseif (substr($field, 0, 5) == 'case_') {
696 if ($query->_fields['case'][$field]['title']) {
697 $headerRows[] = $query->_fields['case'][$field]['title'];
698 }
699 elseif ($query->_fields['activity'][$field]['title']) {
700 $headerRows[] = $query->_fields['activity'][$field]['title'];
701 }
702 }
703 elseif (array_key_exists($field, $contactRelationshipTypes)) {
704 $relName = $field;
705 foreach ($value as $relationField => $relationValue) {
706 // below block is same as primary block (duplicate)
707 if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
708 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
709 $headerName = $field . '-' . $relationField;
710 }
711 else {
712 if ($relationField == 'current_employer') {
713 $headerName = $field . '-' . 'current_employer';
714 }
715 else {
716 $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
717 }
718 }
719
720 $headerRows[] = $headerName;
721
722 self::sqlColumnDefn($query, $sqlColumns, $headerName);
723 }
724 elseif ($relationField == 'phone_type_id') {
725 $headerName = $field . '-' . 'Phone Type';
726 $headerRows[] = $headerName;
727 self::sqlColumnDefn($query, $sqlColumns, $headerName);
728 }
729 elseif ($relationField == 'provider_id') {
730 $headerName = $field . '-' . 'Im Service Provider';
731 $headerRows[] = $headerName;
732 self::sqlColumnDefn($query, $sqlColumns, $headerName);
733 }
734 elseif ($relationField == 'state_province_id') {
735 $headerName = $field . '-' . 'state_province_id';
736 $headerRows[] = $headerName;
737 self::sqlColumnDefn($query, $sqlColumns, $headerName);
738 }
739 elseif (is_array($relationValue) && $relationField == 'location') {
740 // fix header for location type case
741 foreach ($relationValue as $ltype => $val) {
742 foreach (array_keys($val) as $fld) {
743 $type = explode('-', $fld);
744
745 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
746
747 if (CRM_Utils_Array::value(1, $type)) {
748 if (CRM_Utils_Array::value(0, $type) == 'phone') {
749 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
750 }
751 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
752 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
753 }
754 }
755 $headerName = $field . '-' . $hdr;
756 $headerRows[] = $headerName;
757 self::sqlColumnDefn($query, $sqlColumns, $headerName);
758 }
759 }
760 }
761 }
762 }
d77aba4b
AS
763 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
764 $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
765 }
6a488035
TO
766 else {
767 $headerRows[] = $field;
768 }
769
770 if (!$sqlDone) {
771 self::sqlColumnDefn($query, $sqlColumns, $field);
772 }
773 }
774
775 // add im_provider to $dao object
776 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
777 $dao->im_provider = $dao->provider_id;
778 }
779
780 //build row values (data)
781 $fieldValue = NULL;
782 if (property_exists($dao, $field)) {
783 $fieldValue = $dao->$field;
784 // to get phone type from phone type id
785 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
786 $fieldValue = $phoneTypes[$fieldValue];
787 }
788 elseif ($field == 'provider_id' || $field == 'im_provider') {
789 $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
790 }
791 elseif ($field == 'participant_role_id') {
792 $participantRoles = CRM_Event_PseudoConstant::participantRole();
793 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
794 $viewRoles = array();
795 foreach (explode($sep, $dao->$field) as $k => $v) {
796 $viewRoles[] = $participantRoles[$v];
797 }
798 $fieldValue = implode(',', $viewRoles);
799 }
800 elseif ($field == 'master_id') {
801 $masterAddressId = NULL;
802 if (isset($dao->master_id)) {
803 $masterAddressId = $dao->master_id;
804 }
805 // get display name of contact that address is shared.
806 $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $dao->contact_id);
807 }
808 }
809
810 if ($field == 'id') {
811 $row[$field] = $dao->contact_id;
812 // special case for calculated field
813 }
d4a280d8 814 elseif ($field == 'source_contact_id') {
815 $row[$field] = $dao->contact_id;
816 }
6a488035
TO
817 elseif ($field == 'pledge_balance_amount') {
818 $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
819 // special case for calculated field
820 }
821 elseif ($field == 'pledge_next_pay_amount') {
822 $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
823 }
824 elseif (is_array($value) && $field == 'location') {
825 // fix header for location type case
826 foreach ($value as $ltype => $val) {
827 foreach (array_keys($val) as $fld) {
828 $type = explode('-', $fld);
829 $fldValue = "{$ltype}-" . $type[0];
6f7e23df
CW
830 // CRM-14076 - fix label to work as the query object expects
831 // FIXME: We should not be using labels as keys!
832 $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0];
6a488035
TO
833
834 if (CRM_Utils_Array::value(1, $type)) {
835 $fldValue .= "-" . $type[1];
3d4498eb 836 $daoField .= "-" . $type[1];
6a488035
TO
837 }
838
839 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
840 switch ($fld) {
841 case 'country':
842 case 'world_region':
6f7e23df 843 $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'country'));
6a488035
TO
844 break;
845
846 case 'state_province':
6f7e23df 847 $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'province'));
6a488035
TO
848 break;
849
850 case 'im_provider':
6f7e23df 851 $imFieldvalue = $daoField . "-provider_id";
6a488035
TO
852 $row[$fldValue] = CRM_Utils_Array::value($dao->$imFieldvalue, $imProviders);
853 break;
854
855 default:
6f7e23df 856 $row[$fldValue] = $dao->$daoField;
6a488035
TO
857 break;
858 }
859 }
860 }
861 }
862 elseif (array_key_exists($field, $contactRelationshipTypes)) {
863 $relDAO = CRM_Utils_Array::value($dao->contact_id, $allRelContactArray[$field]);
864 foreach ($value as $relationField => $relationValue) {
865 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
866 $fieldValue = $relDAO->$relationField;
867 if ($relationField == 'phone_type_id') {
868 $fieldValue = $phoneTypes[$relationValue];
869 }
870 elseif ($relationField == 'provider_id') {
871 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
872 }
873 }
2bf55c30 874 // CRM-13995
908f91d0 875 elseif (is_object($relDAO) && in_array($relationField, array(
2bf55c30
BS
876 'email_greeting', 'postal_greeting', 'addressee'))) {
877 //special case for greeting replacement
878 $fldValue = "{$relationField}_display";
879 $fieldValue = $relDAO->$fldValue;
880 }
881 elseif ( is_object($relDAO) && $relationField == 'state_province' ) {
882 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
883 }
b07c1873
DG
884 elseif ( is_object($relDAO) && $relationField == 'country' ) {
885 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
886 }
6a488035
TO
887 else {
888 $fieldValue = '';
889 }
890 $field = $field . '_';
2bf55c30 891
6a488035
TO
892 if (is_object($relDAO) && $relationField == 'id') {
893 $row[$field . $relationField] = $relDAO->contact_id;
2bf55c30
BS
894 }
895 elseif ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
6a488035
TO
896 foreach ($relationValue as $ltype => $val) {
897 foreach (array_keys($val) as $fld) {
898 $type = explode('-', $fld);
899 $fldValue = "{$ltype}-" . $type[0];
900 if (CRM_Utils_Array::value(1, $type)) {
901 $fldValue .= "-" . $type[1];
902 }
903 // CRM-3157: localise country, region (both have ‘country’ context)
904 // and state_province (‘province’ context)
905 switch (TRUE) {
906 case (!is_object($relDAO)):
907 $row[$field . '_' . $fldValue] = '';
908 break;
909
910 case in_array('country', $type):
911 case in_array('world_region', $type):
912 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
913 array('context' => 'country')
914 );
915 break;
916
917 case in_array('state_province', $type):
918 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
919 array('context' => 'province')
920 );
921 break;
922
923 default:
924 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
925 break;
926 }
927 }
928 }
929 }
930 elseif (isset($fieldValue) && $fieldValue != '') {
931 //check for custom data
932 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
933 $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID,
934 $relationQuery[$field]->_options
935 );
936 }
6a488035
TO
937 else {
938 //normal relationship fields
939 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
940 switch ($relationField) {
941 case 'country':
942 case 'world_region':
943 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
944 break;
945
946 case 'state_province':
947 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
948 break;
949
950 default:
951 $row[$field . $relationField] = $fieldValue;
952 break;
953 }
954 }
955 }
956 else {
957 // if relation field is empty or null
958 $row[$field . $relationField] = '';
959 }
960 }
961 }
962 elseif (isset($fieldValue) &&
963 $fieldValue != ''
964 ) {
965 //check for custom data
966 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
967 $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
968 }
969 elseif (array_key_exists($field, $multipleSelectFields)) {
970 //option group fixes
971 $paramsNew = array($field => $fieldValue);
972 if ($field == 'test_tutoring') {
973 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
974 // for readers group
975 }
976 elseif (substr($field, 0, 4) == 'cmr_') {
977 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
978 }
979 else {
980 $name = array($field => array('newName' => $field, 'groupName' => $field));
981 }
982 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
983 $row[$field] = $paramsNew[$field];
984 }
985 elseif (in_array($field, array(
986 'email_greeting', 'postal_greeting', 'addressee'))) {
987 //special case for greeting replacement
988 $fldValue = "{$field}_display";
989 $row[$field] = $dao->$fldValue;
990 }
991 else {
992 //normal fields with a touch of CRM-3157
993 switch ($field) {
994 case 'country':
995 case 'world_region':
996 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
997 break;
998
999 case 'state_province':
1000 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1001 break;
1002
1003 case 'gender':
1004 case 'preferred_communication_method':
1005 case 'preferred_mail_format':
1006 $row[$field] = $i18n->crm_translate($fieldValue);
1007 break;
1008
1009 default:
1010 $row[$field] = $fieldValue;
1011 break;
1012 }
1013 }
1014 }
1015 elseif (substr($field, -8) == 'campaign') {
1016 $campIdFld = "{$field}_id";
1017 $row[$field] = CRM_Utils_Array::value($dao->$campIdFld, $allCampaigns, '');
1018 }
d77aba4b
AS
1019 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
1020 $paymentData = CRM_Utils_Array::value($dao->$paymentTableId, $paymentDetails);
1021 $payFieldMapper = array(
1022 'componentPaymentField_total_amount' => 'total_amount',
1023 'componentPaymentField_contribution_status' => 'contribution_status',
1024 'componentPaymentField_payment_instrument' => 'pay_instru',
1025 'componentPaymentField_transaction_id' => 'trxn_id',
1026 'componentPaymentField_received_date' => 'receive_date',
1027 );
1028 $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
1029 }
6a488035
TO
1030 else {
1031 // if field is empty or null
1032 $row[$field] = '';
1033 }
1034 }
1035
1036 // add payment headers if required
1037 if ($addPaymentHeader && $paymentFields) {
1038 $headerRows = array_merge($headerRows, $paymentHeaders);
1039 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1040 self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1041 }
6a488035
TO
1042 }
1043
1044 if ($setHeader) {
1045 $exportTempTable = self::createTempTable($sqlColumns);
1046 }
1047
1048 //build header only once
1049 $setHeader = FALSE;
1050
e026db3c 1051 // If specific payment fields have been selected for export, payment
545285b8 1052 // data will already be in $row. Otherwise, add payment related
e026db3c 1053 // information, if appropriate.
fc33177b 1054 if ($addPaymentHeader) {
1055 if (!$selectedPaymentFields) {
1056 if ($paymentFields) {
1057 $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
1058 if (!is_array($paymentData) || empty($paymentData)) {
1059 $paymentData = $nullContributionDetails;
1060 }
1061 $row = array_merge($row, $paymentData);
1062 }
1063 elseif (!empty($paymentDetails)) {
1064 $row = array_merge($row, $nullContributionDetails);
e026db3c 1065 }
e026db3c 1066 }
6a488035 1067 }
6a488035
TO
1068 //remove organization name for individuals if it is set for current employer
1069 if (CRM_Utils_Array::value('contact_type', $row) &&
1070 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1071 ) {
1072 $row['organization_name'] = '';
1073 }
1074
1075 // add component info
1076 // write the row to a file
1077 $componentDetails[] = $row;
1078
1079 // output every $tempRowCount rows
1080 if ($count % $tempRowCount == 0) {
1081 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1082 $componentDetails = array();
1083 }
1084 }
1085 $dao->free();
1086 $offset += $rowCount;
1087 }
1088
1089 if ($exportTempTable) {
1090 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1091
1092 // do merge same address and merge same household processing
1093 if ($mergeSameAddress) {
1094 self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1095 }
1096
1097 // merge the records if they have corresponding households
1098 if ($mergeSameHousehold) {
1099 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1100 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1101 }
1102
1103 // fix the headers for rows with relationship type
1104 if (!empty($relName)) {
1105 self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1106 }
1107
1108 // if postalMailing option is checked, exclude contacts who are deceased, have
1109 // "Do not mail" privacy setting, or have no street address
1110 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1111 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1112 ) {
1113 self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1114 }
1115
1116 // call export hook
1117 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1118
1119 // now write the CSV file
1120 self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1121
1122 // delete the export temp table and component table
1123 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1124 CRM_Core_DAO::executeQuery($sql);
1125
1126 CRM_Utils_System::civiExit();
1127 }
1128 else {
1129 CRM_Core_Error::fatal(ts('No records to export'));
1130 }
1131 }
1132
1133 /**
1134 * name of the export file based on mode
1135 *
1136 * @param string $output type of output
1137 * @param int $mode export mode
1138 *
1139 * @return string name of the file
1140 */
25acfd6b 1141 static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select::CONTACT_EXPORT) {
6a488035
TO
1142 switch ($mode) {
1143 case CRM_Export_Form_Select::CONTACT_EXPORT:
1144 return ts('CiviCRM Contact Search');
1145
1146 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
1147 return ts('CiviCRM Contribution Search');
1148
1149 case CRM_Export_Form_Select::MEMBER_EXPORT:
1150 return ts('CiviCRM Member Search');
1151
1152 case CRM_Export_Form_Select::EVENT_EXPORT:
1153 return ts('CiviCRM Participant Search');
1154
1155 case CRM_Export_Form_Select::PLEDGE_EXPORT:
1156 return ts('CiviCRM Pledge Search');
1157
1158 case CRM_Export_Form_Select::CASE_EXPORT:
1159 return ts('CiviCRM Case Search');
1160
1161 case CRM_Export_Form_Select::GRANT_EXPORT:
1162 return ts('CiviCRM Grant Search');
1163
1164 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
1165 return ts('CiviCRM Activity Search');
1166 }
1167 }
1168
1169 /**
1170 * Function to handle import error file creation.
1171 *
1172 */
c27ca2c8 1173 static function invoke() {
6a488035
TO
1174 $type = CRM_Utils_Request::retrieve('type', 'Positive', CRM_Core_DAO::$_nullObject);
1175 $parserName = CRM_Utils_Request::retrieve('parser', 'String', CRM_Core_DAO::$_nullObject);
1176 if (empty($parserName) || empty($type)) {
1177 return;
1178 }
1179
1180 // clean and ensure parserName is a valid string
1181 $parserName = CRM_Utils_String::munge($parserName);
1182 $parserClass = explode('_', $parserName);
1183
1184 // make sure parserClass is in the CRM namespace and
1185 // at least 3 levels deep
1186 if ($parserClass[0] == 'CRM' &&
1187 count($parserClass) >= 3
1188 ) {
1189 require_once (str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php");
1190 // ensure the functions exists
1191 if (method_exists($parserName, 'errorFileName') &&
1192 method_exists($parserName, 'saveFileName')
1193 ) {
1194 $errorFileName = $parserName::errorFileName($type);
1195 $saveFileName = $parserName::saveFileName($type);
1196 if (!empty($errorFileName) && !empty($saveFileName)) {
1197 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1198 header('Content-Description: File Transfer');
1199 header('Content-Type: text/csv');
1200 header('Content-Length: ' . filesize($errorFileName));
1201 header('Content-Disposition: attachment; filename=' . $saveFileName);
1202
1203 readfile($errorFileName);
1204 }
1205 }
1206 }
1207 CRM_Utils_System::civiExit();
1208 }
1209
c27ca2c8 1210 static function exportCustom($customSearchClass, $formValues, $order) {
6a488035
TO
1211 $ext = CRM_Extension_System::singleton()->getMapper();
1212 if (!$ext->isExtensionClass($customSearchClass)) {
1213 require_once (str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php');
1214 }
1215 else {
1216 require_once ($ext->classToPath($customSearchClass));
1217 }
1218 $search = new $customSearchClass($formValues);
1219
1220 $includeContactIDs = FALSE;
1221 if ($formValues['radio_ts'] == 'ts_sel') {
1222 $includeContactIDs = TRUE;
1223 }
1224
1225 $sql = $search->all(0, 0, $order, $includeContactIDs);
1226
1227 $columns = $search->columns();
1228
1229 $header = array_keys($columns);
1230 $fields = array_values($columns);
1231
1232 $rows = array();
1233 $dao = CRM_Core_DAO::executeQuery($sql);
1234 $alterRow = FALSE;
1235 if (method_exists($search, 'alterRow')) {
1236 $alterRow = TRUE;
1237 }
1238 while ($dao->fetch()) {
1239 $row = array();
1240
1241 foreach ($fields as $field) {
1242 $row[$field] = $dao->$field;
1243 }
1244 if ($alterRow) {
1245 $search->alterRow($row);
1246 }
1247 $rows[] = $row;
1248 }
1249
1250 CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName(), $header, $rows);
1251 CRM_Utils_System::civiExit();
1252 }
1253
1254 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
0944820d 1255 if (substr($field, -4) == '_a_b' || substr($field, -4) == '_b_a') {
6a488035
TO
1256 return;
1257 }
1258
1259 $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
1260 if ($fieldName == 'id') {
1261 $fieldName = 'civicrm_primary_id';
1262 }
1263
0944820d
DL
1264 // early exit for master_id, CRM-12100
1265 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1266 if ($fieldName == 'master_id') {
1267 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1268 return;
1269 }
1270
6a488035
TO
1271 // set the sql columns
1272 if (isset($query->_fields[$field]['type'])) {
1273 switch ($query->_fields[$field]['type']) {
1274 case CRM_Utils_Type::T_INT:
6a488035
TO
1275 case CRM_Utils_Type::T_BOOLEAN:
1276 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1277 break;
1278
1279 case CRM_Utils_Type::T_STRING:
1280 if (isset($query->_fields[$field]['maxlength'])) {
1281 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1282 }
1283 else {
1284 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1285 }
1286 break;
1287
1288 case CRM_Utils_Type::T_TEXT:
1289 case CRM_Utils_Type::T_LONGTEXT:
1290 case CRM_Utils_Type::T_BLOB:
1291 case CRM_Utils_Type::T_MEDIUMBLOB:
1292 $sqlColumns[$fieldName] = "$fieldName longtext";
1293 break;
1294
1295 case CRM_Utils_Type::T_FLOAT:
1296 case CRM_Utils_Type::T_ENUM:
1297 case CRM_Utils_Type::T_DATE:
1298 case CRM_Utils_Type::T_TIME:
1299 case CRM_Utils_Type::T_TIMESTAMP:
1300 case CRM_Utils_Type::T_MONEY:
1301 case CRM_Utils_Type::T_EMAIL:
1302 case CRM_Utils_Type::T_URL:
1303 case CRM_Utils_Type::T_CCNUM:
1304 default:
1305 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1306 break;
1307 }
1308 }
1309 else {
1310 if (substr($fieldName, -3, 3) == '_id') {
1338f0b1
DL
1311 // for trxn_id and its variants use a longer buffer
1312 // to accomodate different systems - CRM-13739
1313 static $notRealIDFields = NULL;
1314 if ($notRealIDFields == NULL) {
1315 $notRealIDFields = array( 'trxn_id', 'componentpaymentfield_transaction_id' );
1316 }
1317
1318 if (in_array($fieldName, $notRealIDFields)) {
1319 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1320 }
1321 else {
1322 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1323 }
6a488035
TO
1324 }
1325 else {
1326 $changeFields = array(
1327 'groups',
1328 'tags',
1329 'notes'
1330 );
1331
1332 if (in_array($fieldName, $changeFields)) {
1333 $sqlColumns[$fieldName] = "$fieldName text";
1334 }
1335 else {
1336 // set the sql columns for custom data
1337 if (isset($query->_fields[$field]['data_type'])) {
1338
1339 switch ($query->_fields[$field]['data_type']) {
1340 case 'Country':
1341 case 'StateProvince':
1342 case 'Link':
1343 case 'String':
1344 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1345 break;
1346
1347 case 'Memo':
1348 $sqlColumns[$fieldName] = "$fieldName text";
1349 break;
1350
1351 default:
1352 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1353 break;
1354 }
1355 }
1356 else {
1357 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1358 }
1359 }
1360 }
1361 }
1362 }
1363
1364 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1365 if (empty($details)) {
1366 return;
1367 }
1368
1369 $sql = "
1370SELECT max(id)
1371FROM $tableName
1372";
1373
1374 $id = CRM_Core_DAO::singleValueQuery($sql);
1375 if (!$id) {
1376 $id = 0;
1377 }
1378
1379 $sqlClause = array();
1380
1381 foreach ($details as $dontCare => $row) {
1382 $id++;
1383 $valueString = array($id);
1384 foreach ($row as $dontCare => $value) {
1385 if (empty($value)) {
1386 $valueString[] = "''";
1387 }
1388 else {
1389 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
1390 }
1391 }
1392 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1393 }
1394
1395 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1396
1397 $sqlValueString = implode(",\n", $sqlClause);
1398
1399 $sql = "
1400INSERT INTO $tableName $sqlColumnString
1401VALUES $sqlValueString
1402";
1403
1404 CRM_Core_DAO::executeQuery($sql);
1405 }
1406
1407 static function createTempTable(&$sqlColumns) {
1408 //creating a temporary table for the search result that need be exported
1409 $exportTempTable = CRM_Core_DAO::createTempTableName('civicrm_export', TRUE);
1410
1411 // also create the sql table
1412 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1413 CRM_Core_DAO::executeQuery($sql);
1414
1415 $sql = "
1416CREATE TABLE {$exportTempTable} (
1417 id int unsigned NOT NULL AUTO_INCREMENT,
1418";
1419 $sql .= implode(",\n", array_values($sqlColumns));
1420
1421 $sql .= ",
1422 PRIMARY KEY ( id )
1423";
1424 // add indexes for street_address and household_name if present
1425 $addIndices = array(
1426 'street_address',
1427 'household_name',
1428 'civicrm_primary_id',
1429 );
1430
1431 foreach ($addIndices as $index) {
1432 if (isset($sqlColumns[$index])) {
1433 $sql .= ",
1434 INDEX index_{$index}( $index )
1435";
1436 }
1437 }
1438
1439 $sql .= "
1440) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1441";
1442
1443 CRM_Core_DAO::executeQuery($sql);
1444 return $exportTempTable;
1445 }
1446
1447 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1448 // check if any records are present based on if they have used shared address feature,
1449 // and not based on if city / state .. matches.
1450 $sql = "
1451SELECT r1.id as copy_id,
1452 r1.civicrm_primary_id as copy_contact_id,
1453 r1.addressee as copy_addressee,
1454 r1.addressee_id as copy_addressee_id,
1455 r1.postal_greeting as copy_postal_greeting,
1456 r1.postal_greeting_id as copy_postal_greeting_id,
1457 r2.id as master_id,
1458 r2.civicrm_primary_id as master_contact_id,
1459 r2.postal_greeting as master_postal_greeting,
1460 r2.postal_greeting_id as master_postal_greeting_id,
1461 r2.addressee as master_addressee,
1462 r2.addressee_id as master_addressee_id
1463FROM $tableName r1
1464INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1465INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1466ORDER BY r1.id";
1467 $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE);
1468
1469 // find all the records that have the same street address BUT not in a household
1470 // require match on city and state as well
1471 $sql = "
1472SELECT r1.id as master_id,
1473 r1.civicrm_primary_id as master_contact_id,
1474 r1.postal_greeting as master_postal_greeting,
1475 r1.postal_greeting_id as master_postal_greeting_id,
1476 r1.addressee as master_addressee,
1477 r1.addressee_id as master_addressee_id,
1478 r2.id as copy_id,
1479 r2.civicrm_primary_id as copy_contact_id,
1480 r2.postal_greeting as copy_postal_greeting,
1481 r2.postal_greeting_id as copy_postal_greeting_id,
1482 r2.addressee as copy_addressee,
1483 r2.addressee_id as copy_addressee_id
1484FROM $tableName r1
1485LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1486 r1.city = r2.city AND
1487 r1.state_province_id = r2.state_province_id )
1488WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1489AND ( r2.household_name IS NULL OR r2.household_name = '' )
1490AND ( r1.street_address != '' )
1491AND r2.id > r1.id
1492ORDER BY r1.id
1493";
1494 $merge = self::_buildMasterCopyArray($sql, $exportParams);
1495
1496 // unset ids from $merge already present in $linkedMerge
1497 foreach ($linkedMerge as $masterID => $values) {
1498 $keys = array($masterID);
1499 $keys = array_merge($keys, array_keys($values['copy']));
1500 foreach ($merge as $mid => $vals) {
1501 if (in_array($mid, $keys)) {
1502 unset($merge[$mid]);
1503 }
1504 else {
1505 foreach ($values['copy'] as $copyId) {
1506 if (in_array($copyId, $keys)) {
1507 unset($merge[$mid]['copy'][$copyId]);
1508 }
1509 }
1510 }
1511 }
1512 }
1513 $merge = $merge + $linkedMerge;
1514
1515 foreach ($merge as $masterID => $values) {
1516 $sql = "
1517UPDATE $tableName
1518SET addressee = %1, postal_greeting = %2, email_greeting = %3
1519WHERE id = %4
1520";
1521 $params = array(1 => array($values['addressee'], 'String'),
1522 2 => array($values['postalGreeting'], 'String'),
1523 3 => array($values['emailGreeting'], 'String'),
1524 4 => array($masterID, 'Integer'),
1525 );
1526 CRM_Core_DAO::executeQuery($sql, $params);
1527
1528 // delete all copies
1529 $deleteIDs = array_keys($values['copy']);
1530 $deleteIDString = implode(',', $deleteIDs);
1531 $sql = "
1532DELETE FROM $tableName
1533WHERE id IN ( $deleteIDString )
1534";
1535 CRM_Core_DAO::executeQuery($sql);
1536 }
1537
1538 // unset temporary columns that were added for postal mailing format
1539 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1540 $unsetKeys = array_keys($sqlColumns);
1541 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1542 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1543 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1544 }
1545 }
1546 }
1547 }
1548
1549 static function _replaceMergeTokens($contactId, $exportParams) {
1550 $greetings = array();
1551 $contact = NULL;
1552
1553 $greetingFields = array(
1554 'postal_greeting',
1555 'addressee',
1556 );
1557 foreach ($greetingFields as $greeting) {
1558 if (CRM_Utils_Array::value($greeting, $exportParams)) {
1559 $greetingLabel = $exportParams[$greeting];
1560 if (empty($contact)) {
1561 $values = array(
1562 'id' => $contactId,
1563 'version' => 3,
1564 );
1565 $contact = civicrm_api('contact', 'get', $values);
1566
1567 if (CRM_Utils_Array::value('is_error', $contact)) {
1568 return $greetings;
1569 }
1570 $contact = $contact['values'][$contact['id']];
1571 }
1572
1573 $tokens = array('contact' => $greetingLabel);
1574 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1575 }
1576 }
1577 return $greetings;
1578 }
1579
1580 /**
1581 * The function unsets static part of the string, if token is the dynamic part.
1582 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1583 * i.e 'Hello Alan' => converted to => 'Alan'
1584 *
1585 */
1586 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1587 $addressMergeGreetings, $greetingType = 'postal_greeting'
1588 ) {
1589 if (CRM_Utils_Array::value($greetingType, $addressMergeGreetings)) {
1590 $greetingLabel = $addressMergeGreetings[$greetingType];
1591 }
1592 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
1593
1594 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1595 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1596 foreach ($stringsToBeReplaced as $key => $string) {
1597 // to keep one space
1598 $stringsToBeReplaced[$key] = ltrim($string);
1599 }
1600 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1601
1602 return $parsedString;
1603 }
1604
1605 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1606 static $contactGreetingTokens = array();
1607
1608 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
1609 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
1610
1611 $merge = $parents = array();
1612 $dao = CRM_Core_DAO::executeQuery($sql);
1613
1614 while ($dao->fetch()) {
1615 $masterID = $dao->master_id;
1616 $copyID = $dao->copy_id;
1617 $masterPostalGreeting = $dao->master_postal_greeting;
1618 $masterAddressee = $dao->master_addressee;
1619 $copyAddressee = $dao->copy_addressee;
1620
1621 if (!$sharedAddress) {
1622 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
1623 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
1624 }
1625 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1626 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
1627 );
1628 $masterAddressee = CRM_Utils_Array::value('addressee',
1629 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
1630 );
1631
1632 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
1633 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
1634 }
1635 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1636 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
1637 );
1638 $copyAddressee = CRM_Utils_Array::value('addressee',
1639 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
1640 );
1641 }
1642
1643 if (!isset($merge[$masterID])) {
1644 // check if this is an intermediate child
1645 // this happens if there are 3 or more matches a,b, c
1646 // the above query will return a, b / a, c / b, c
1647 // we might be doing a bit more work, but for now its ok, unless someone
1648 // knows how to fix the query above
1649 if (isset($parents[$masterID])) {
1650 $masterID = $parents[$masterID];
1651 }
1652 else {
1653 $merge[$masterID] = array(
1654 'addressee' => $masterAddressee,
1655 'copy' => array(),
1656 'postalGreeting' => $masterPostalGreeting,
1657 );
1658 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1659 }
1660 }
1661 $parents[$copyID] = $masterID;
1662
1663 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1664
1665 if (CRM_Utils_Array::value('postal_greeting_other', $exportParams) &&
1666 count($merge[$masterID]['copy']) >= 1
1667 ) {
1668 // use static greetings specified if no of contacts > 2
1669 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1670 }
1671 elseif ($copyPostalGreeting) {
1672 self::_trimNonTokens($copyPostalGreeting,
1673 $postalOptions[$dao->copy_postal_greeting_id],
1674 $exportParams
1675 );
1676 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1677 // if there happens to be a duplicate, remove it
1678 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1679 }
1680
1681 if (CRM_Utils_Array::value('addressee_other', $exportParams) &&
1682 count($merge[$masterID]['copy']) >= 1
1683 ) {
1684 // use static greetings specified if no of contacts > 2
1685 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1686 }
1687 elseif ($copyAddressee) {
1688 self::_trimNonTokens($copyAddressee,
1689 $addresseeOptions[$dao->copy_addressee_id],
1690 $exportParams, 'addressee'
1691 );
1692 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1693 }
1694 }
1695 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1696 }
1697
1698 return $merge;
1699 }
1700
1701 /**
1702 * Function to merge household record into the individual record
1703 * if exists
1704 *
1705 * @param string $exportTempTable temporary temp table that stores the records
1706 * @param array $headerRows array of headers for the export file
1707 * @param array $sqlColumns array of names of the table columns of the temp table
1708 * @param string $prefix name of the relationship type that is prefixed to the table columns
1709 */
1710 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1711 $prefixColumn = $prefix . '_';
1712 $allKeys = array_keys($sqlColumns);
1713 $replaced = array();
1714 $headerRows = array_values($headerRows);
1715
1716 // name map of the non standard fields in header rows & sql columns
1717 $mappingFields = array(
1718 'civicrm_primary_id' => 'id',
1719 'contact_source' => 'source',
1720 'current_employer_id' => 'employer_id',
1721 'contact_is_deleted' => 'is_deleted',
1722 'name' => 'address_name',
1723 'provider_id' => 'im_service_provider',
1724 'phone_type_id' => 'phone_type'
1725 );
1726
1727 //figure out which columns are to be replaced by which ones
1728 foreach ($sqlColumns as $columnNames => $dontCare) {
1729 if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) {
1730 $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64);
1731 }
1732 else {
1733 $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64);
1734
1735 if (CRM_Utils_Array::value($householdColName, $sqlColumns)) {
1736 $replaced[$columnNames] = $householdColName;
1737 }
1738 }
1739 }
1740 $query = "UPDATE $exportTempTable SET ";
1741
1742 $clause = array();
1743 foreach ($replaced as $from => $to) {
1744 $clause[] = "$from = $to ";
1745 unset($sqlColumns[$to]);
1746 if ($key = CRM_Utils_Array::key($to, $allKeys)) {
1747 unset($headerRows[$key]);
1748 }
1749 }
1750 $query .= implode(",\n", $clause);
1751 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1752
1753 CRM_Core_DAO::executeQuery($query);
1754
1755 //drop the table columns that store redundant household info
1756 $dropQuery = "ALTER TABLE $exportTempTable ";
1757 foreach ($replaced as $householdColumns) {
1758 $dropClause[] = " DROP $householdColumns ";
1759 }
1760 $dropQuery .= implode(",\n", $dropClause);
1761
1762 CRM_Core_DAO::executeQuery($dropQuery);
1763
1764 // also drop the temp table if exists
1765 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1766 CRM_Core_DAO::executeQuery($sql);
1767
1768 // clean up duplicate records
1769 $query = "
1770CREATE TABLE {$exportTempTable}_temp SELECT *
1771FROM {$exportTempTable}
1772GROUP BY civicrm_primary_id ";
1773
1774 CRM_Core_DAO::executeQuery($query);
1775
1776 $query = "DROP TABLE $exportTempTable";
1777 CRM_Core_DAO::executeQuery($query);
1778
1779 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1780 CRM_Core_DAO::executeQuery($query);
1781 }
1782
1783 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1784 $writeHeader = TRUE;
1785 $offset = 0;
1786 $limit = self::EXPORT_ROW_COUNT;
1787
1788 $query = "SELECT * FROM $exportTempTable";
1789
1790 while (1) {
1791 $limitQuery = $query . "
1792LIMIT $offset, $limit
1793";
1794 $dao = CRM_Core_DAO::executeQuery($limitQuery);
1795
1796 if ($dao->N <= 0) {
1797 break;
1798 }
1799
1800 $componentDetails = array();
1801 while ($dao->fetch()) {
1802 $row = array();
1803
1804 foreach ($sqlColumns as $column => $dontCare) {
1805 $row[$column] = $dao->$column;
1806 }
1807 $componentDetails[] = $row;
1808 }
1809 if ( $exportMode == 'financial' ) {
1810 $getExportFileName = 'CiviCRM Contribution Search';
1811 }
1812 else {
1813 $getExportFileName =self::getExportFileName( 'csv', $exportMode );
1814 }
1815 $csvRows = CRM_Core_Report_Excel::writeCSVFile( $getExportFileName,
1816 $headerRows,
1817 $componentDetails,
1818 null,
1819 $writeHeader,
1820 $saveFile );
1821
1822 if ($saveFile && !empty($csvRows)) {
1823 $batchItems .= $csvRows;
1824 }
1825
1826 $writeHeader = false;
1827 $offset += $limit;
1828 }
1829 }
1830
1831 /**
1832 * Function to manipulate header rows for relationship fields
1833 *
1834 */
1571c7e7 1835 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
6a488035
TO
1836 foreach ($headerRows as & $header) {
1837 $split = explode('-', $header);
1838 if ($relationTypeName = CRM_Utils_Array::value($split[0], $contactRelationshipTypes)) {
1839 $split[0] = $relationTypeName;
1840 $header = implode('-', $split);
1841 }
1842 }
1843 }
1844
1845 /**
1846 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1847 * or have no street address
1848 *
1849 */
c27ca2c8 1850 static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
6a488035
TO
1851 $whereClause = array();
1852
1853 if (array_key_exists('is_deceased', $sqlColumns)) {
1854 $whereClause[] = 'is_deceased = 1';
1855 }
1856
1857 if (array_key_exists('do_not_mail', $sqlColumns)) {
1858 $whereClause[] = 'do_not_mail = 1';
1859 }
1860
1861 if (array_key_exists('street_address', $sqlColumns)) {
1862 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1863
1864 // check for supplemental_address_1
1865 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1866 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1867 'address_options', TRUE, NULL, TRUE
1868 );
1869 if (CRM_Utils_Array::value('supplemental_address_1', $addressOptions)) {
1870 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1871 // enclose it again, since we are doing an AND in between a set of ORs
1872 $addressWhereClause = "( $addressWhereClause )";
1873 }
1874 }
1875
1876 $whereClause[] = $addressWhereClause;
1877 }
1878
1879 if (!empty($whereClause)) {
1880 $whereClause = implode(' OR ', $whereClause);
1881 $query = "
1882DELETE
1883FROM $exportTempTable
1884WHERE {$whereClause}";
1885 CRM_Core_DAO::singleValueQuery($query);
1886 }
1887
1888 // unset temporary columns that were added for postal mailing format
1889 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1890 $unsetKeys = array_keys($sqlColumns);
1891 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1892 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1893 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1894 }
1895 }
1896 }
1897 }
d77aba4b
AS
1898
1899 /**
1900 * Build componentPayment fields.
1901 */
1902 static function componentPaymentFields() {
1903 static $componentPaymentFields;
1904 if (!isset( $componentPaymentFields)) {
1905 $componentPaymentFields = array(
1906 'componentPaymentField_total_amount' => ts('Total Amount'),
1907 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1908 'componentPaymentField_received_date' => ts('Received Date'),
1909 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1910 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1911 );
1912 }
1913 return $componentPaymentFields;
1914 }
6a488035
TO
1915}
1916