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