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