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