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