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