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