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