Merge pull request #2687 from giant-rabbit/event_info_custom_validation
[civicrm-core.git] / CRM / Export / BAO / Export.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 31 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
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 311 if ($queryMode == CRM_Contact_BAO_Query::MODE_CONTRIBUTE) {
4f3846df
DS
312 // soft credit columns are not automatically populated, because contribution search doesn't require them by default
313 $componentReturnProperties =
314 array_merge(
315 $componentReturnProperties,
526bdd5e 316 CRM_Contribute_BAO_Query::softCreditReturnProperties(TRUE));
81ec6180 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:
4f3846df
DS
565 $groupBy = 'GROUP BY civicrm_contribution.id';
566 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
567 // especial group by when soft credit columns are included
568 $groupBy = 'GROUP BY contribution_search_scredit_combined.id, contribution_search_scredit_combined.scredit_id';
f654cacf 569 }
8a13a745 570 break;
571
572 case CRM_Export_Form_Select::EVENT_EXPORT:
573 $groupBy = 'GROUP BY civicrm_participant.id';
574 break;
575
576 case CRM_Export_Form_Select::MEMBER_EXPORT:
577 $groupBy = " GROUP BY civicrm_membership.id";
578 break;
579 }
580
6a488035
TO
581 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
582 $groupBy = " GROUP BY civicrm_activity.id ";
583 }
584 $queryString .= $groupBy;
585 if ($order) {
586 list($field, $dir) = explode(' ', $order, 2);
587 $field = trim($field);
a7488080 588 if (!empty($returnProperties[$field])) {
6a488035
TO
589 // $queryString .= " ORDER BY $order";
590 }
591 }
592
593 $multipleSelectFields = array('preferred_communication_method' => 1);
594
595 $addPaymentHeader = FALSE;
596
597 $paymentDetails = array();
d77aba4b 598 if ($paymentFields || $selectedPaymentFields) {
6a488035
TO
599
600 // get payment related in for event and members
601 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
d77aba4b 602 //get all payment headers.
7460c131
AS
603 // If we haven't selected specific payment fields, load in all the
604 // payment headers.
d77aba4b
AS
605 if (!$selectedPaymentFields) {
606 $paymentHeaders = self::componentPaymentFields();
607 if (!empty($paymentDetails)) {
608 $addPaymentHeader = TRUE;
609 }
6a488035 610 }
7460c131
AS
611 // If we have seleted specific payment fields, leave the payment headers
612 // as an empty array; the headers for each selected field will be added
613 // elsewhere.
614 else {
615 $paymentHeaders = array();
616 }
6a488035
TO
617 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
618 }
619
93c29fb5
CW
620 // Split campaign into 2 fields for id and title
621 $campaignReturnProperties = array();
622 foreach ($returnProperties as $fld => $true) {
623 $campaignReturnProperties[$fld] = $true;
624 if (substr($fld, -11) == 'campaign_id') {
625 $exportCampaign = TRUE;
626 $campaignReturnProperties[substr($fld, 0, -3)] = 1;
627 }
628 }
629 $returnProperties = $campaignReturnProperties;
6a488035 630 //get all campaigns.
93c29fb5 631 if (isset($exportCampaign)) {
6a488035
TO
632 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
633 }
634
635 $componentDetails = $headerRows = $sqlColumns = array();
636 $setHeader = TRUE;
637
638 $rowCount = self::EXPORT_ROW_COUNT;
639 $offset = 0;
640 // we write to temp table often to avoid using too much memory
641 $tempRowCount = 100;
642
643 $count = -1;
644
645 // for CRM-3157 purposes
646 $i18n = CRM_Core_I18n::singleton();
647
648 while (1) {
649 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
650 $dao = CRM_Core_DAO::executeQuery($limitQuery);
651 if ($dao->N <= 0) {
652 break;
653 }
654
655 while ($dao->fetch()) {
656 $count++;
657 $row = array();
658
b23943b8 659 //convert the pseudo constants
660 $query->convertToPseudoNames($dao);
d9ab802d 661
6a488035
TO
662 //first loop through returnproperties so that we return what is required, and in same order.
663 $relationshipField = 0;
664 foreach ($returnProperties as $field => $value) {
665 //we should set header only once
666 if ($setHeader) {
667 $sqlDone = FALSE;
93c29fb5
CW
668 // Split campaign into 2 fields for id and title
669 if (substr($field, -8) == 'campaign') {
670 $headerRows[] = ts('Campaign Title');
671 }
672 elseif (substr($field, -11) == 'campaign_id') {
673 $headerRows[] = ts('Campaign ID');
674 }
675 elseif (isset($query->_fields[$field]['title'])) {
6a488035
TO
676 $headerRows[] = $query->_fields[$field]['title'];
677 }
678 elseif ($field == 'phone_type_id') {
679 $headerRows[] = ts('Phone Type');
680 }
681 elseif ($field == 'provider_id') {
682 $headerRows[] = ts('IM Service Provider');
683 }
684 elseif (is_array($value) && $field == 'location') {
685 // fix header for location type case
686 foreach ($value as $ltype => $val) {
687 foreach (array_keys($val) as $fld) {
688 $type = explode('-', $fld);
689 $hdr = "{$ltype}-" . $query->_fields[$type[0]]['title'];
690
a7488080 691 if (!empty($type[1])) {
6a488035
TO
692 if (CRM_Utils_Array::value(0, $type) == 'phone') {
693 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
694 }
695 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
696 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
697 }
698 }
699 $headerRows[] = $hdr;
700 self::sqlColumnDefn($query, $sqlColumns, $hdr);
701 }
702 $sqlDone = TRUE;
703 }
704 }
705 elseif (substr($field, 0, 5) == 'case_') {
706 if ($query->_fields['case'][$field]['title']) {
707 $headerRows[] = $query->_fields['case'][$field]['title'];
708 }
709 elseif ($query->_fields['activity'][$field]['title']) {
710 $headerRows[] = $query->_fields['activity'][$field]['title'];
711 }
712 }
713 elseif (array_key_exists($field, $contactRelationshipTypes)) {
714 $relName = $field;
715 foreach ($value as $relationField => $relationValue) {
716 // below block is same as primary block (duplicate)
717 if (isset($relationQuery[$field]->_fields[$relationField]['title'])) {
718 if ($relationQuery[$field]->_fields[$relationField]['name'] == 'name') {
719 $headerName = $field . '-' . $relationField;
720 }
721 else {
722 if ($relationField == 'current_employer') {
723 $headerName = $field . '-' . 'current_employer';
724 }
725 else {
726 $headerName = $field . '-' . $relationQuery[$field]->_fields[$relationField]['name'];
727 }
728 }
729
730 $headerRows[] = $headerName;
731
732 self::sqlColumnDefn($query, $sqlColumns, $headerName);
733 }
734 elseif ($relationField == 'phone_type_id') {
735 $headerName = $field . '-' . 'Phone Type';
736 $headerRows[] = $headerName;
737 self::sqlColumnDefn($query, $sqlColumns, $headerName);
738 }
739 elseif ($relationField == 'provider_id') {
740 $headerName = $field . '-' . 'Im Service Provider';
741 $headerRows[] = $headerName;
742 self::sqlColumnDefn($query, $sqlColumns, $headerName);
743 }
744 elseif ($relationField == 'state_province_id') {
745 $headerName = $field . '-' . 'state_province_id';
746 $headerRows[] = $headerName;
747 self::sqlColumnDefn($query, $sqlColumns, $headerName);
748 }
749 elseif (is_array($relationValue) && $relationField == 'location') {
750 // fix header for location type case
751 foreach ($relationValue as $ltype => $val) {
752 foreach (array_keys($val) as $fld) {
753 $type = explode('-', $fld);
754
755 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields[$type[0]]['title'];
756
a7488080 757 if (!empty($type[1])) {
6a488035
TO
758 if (CRM_Utils_Array::value(0, $type) == 'phone') {
759 $hdr .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
760 }
761 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
762 $hdr .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
763 }
764 }
765 $headerName = $field . '-' . $hdr;
766 $headerRows[] = $headerName;
767 self::sqlColumnDefn($query, $sqlColumns, $headerName);
768 }
769 }
770 }
771 }
772 }
d77aba4b
AS
773 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
774 $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
775 }
6a488035
TO
776 else {
777 $headerRows[] = $field;
778 }
779
780 if (!$sqlDone) {
781 self::sqlColumnDefn($query, $sqlColumns, $field);
782 }
783 }
784
785 // add im_provider to $dao object
786 if ($field == 'im_provider' && property_exists($dao, 'provider_id')) {
787 $dao->im_provider = $dao->provider_id;
788 }
789
790 //build row values (data)
791 $fieldValue = NULL;
792 if (property_exists($dao, $field)) {
793 $fieldValue = $dao->$field;
794 // to get phone type from phone type id
795 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
796 $fieldValue = $phoneTypes[$fieldValue];
797 }
798 elseif ($field == 'provider_id' || $field == 'im_provider') {
799 $fieldValue = CRM_Utils_Array::value($fieldValue, $imProviders);
800 }
801 elseif ($field == 'participant_role_id') {
802 $participantRoles = CRM_Event_PseudoConstant::participantRole();
803 $sep = CRM_Core_DAO::VALUE_SEPARATOR;
804 $viewRoles = array();
805 foreach (explode($sep, $dao->$field) as $k => $v) {
806 $viewRoles[] = $participantRoles[$v];
807 }
808 $fieldValue = implode(',', $viewRoles);
809 }
810 elseif ($field == 'master_id') {
811 $masterAddressId = NULL;
812 if (isset($dao->master_id)) {
813 $masterAddressId = $dao->master_id;
814 }
815 // get display name of contact that address is shared.
816 $fieldValue = CRM_Contact_BAO_Contact::getMasterDisplayName($masterAddressId, $dao->contact_id);
817 }
818 }
819
820 if ($field == 'id') {
821 $row[$field] = $dao->contact_id;
822 // special case for calculated field
823 }
d4a280d8 824 elseif ($field == 'source_contact_id') {
825 $row[$field] = $dao->contact_id;
826 }
6a488035
TO
827 elseif ($field == 'pledge_balance_amount') {
828 $row[$field] = $dao->pledge_amount - $dao->pledge_total_paid;
829 // special case for calculated field
830 }
831 elseif ($field == 'pledge_next_pay_amount') {
832 $row[$field] = $dao->pledge_next_pay_amount + $dao->pledge_outstanding_amount;
833 }
834 elseif (is_array($value) && $field == 'location') {
835 // fix header for location type case
836 foreach ($value as $ltype => $val) {
837 foreach (array_keys($val) as $fld) {
838 $type = explode('-', $fld);
839 $fldValue = "{$ltype}-" . $type[0];
6f7e23df
CW
840 // CRM-14076 - fix label to work as the query object expects
841 // FIXME: We should not be using labels as keys!
842 $daoField = CRM_Utils_String::munge($ltype) . '-' . $type[0];
6a488035 843
a7488080 844 if (!empty($type[1])) {
6a488035 845 $fldValue .= "-" . $type[1];
3d4498eb 846 $daoField .= "-" . $type[1];
6a488035
TO
847 }
848
849 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
850 switch ($fld) {
851 case 'country':
852 case 'world_region':
6f7e23df 853 $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'country'));
6a488035
TO
854 break;
855
856 case 'state_province':
6f7e23df 857 $row[$fldValue] = $i18n->crm_translate($dao->$daoField, array('context' => 'province'));
6a488035
TO
858 break;
859
860 case 'im_provider':
6f7e23df 861 $imFieldvalue = $daoField . "-provider_id";
6a488035
TO
862 $row[$fldValue] = CRM_Utils_Array::value($dao->$imFieldvalue, $imProviders);
863 break;
864
865 default:
6f7e23df 866 $row[$fldValue] = $dao->$daoField;
6a488035
TO
867 break;
868 }
869 }
870 }
871 }
872 elseif (array_key_exists($field, $contactRelationshipTypes)) {
873 $relDAO = CRM_Utils_Array::value($dao->contact_id, $allRelContactArray[$field]);
874 foreach ($value as $relationField => $relationValue) {
875 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
876 $fieldValue = $relDAO->$relationField;
877 if ($relationField == 'phone_type_id') {
878 $fieldValue = $phoneTypes[$relationValue];
879 }
880 elseif ($relationField == 'provider_id') {
881 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
882 }
883 }
2bf55c30 884 // CRM-13995
908f91d0 885 elseif (is_object($relDAO) && in_array($relationField, array(
2bf55c30
BS
886 'email_greeting', 'postal_greeting', 'addressee'))) {
887 //special case for greeting replacement
888 $fldValue = "{$relationField}_display";
889 $fieldValue = $relDAO->$fldValue;
890 }
891 elseif ( is_object($relDAO) && $relationField == 'state_province' ) {
892 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
893 }
b07c1873
DG
894 elseif ( is_object($relDAO) && $relationField == 'country' ) {
895 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
896 }
6a488035
TO
897 else {
898 $fieldValue = '';
899 }
900 $field = $field . '_';
2bf55c30 901
6a488035
TO
902 if (is_object($relDAO) && $relationField == 'id') {
903 $row[$field . $relationField] = $relDAO->contact_id;
2bf55c30
BS
904 }
905 elseif ( is_object( $relDAO ) && is_array( $relationValue ) && $relationField == 'location' ) {
6a488035
TO
906 foreach ($relationValue as $ltype => $val) {
907 foreach (array_keys($val) as $fld) {
908 $type = explode('-', $fld);
909 $fldValue = "{$ltype}-" . $type[0];
a7488080 910 if (!empty($type[1])) {
6a488035
TO
911 $fldValue .= "-" . $type[1];
912 }
913 // CRM-3157: localise country, region (both have ‘country’ context)
914 // and state_province (‘province’ context)
915 switch (TRUE) {
916 case (!is_object($relDAO)):
917 $row[$field . '_' . $fldValue] = '';
918 break;
919
920 case in_array('country', $type):
921 case in_array('world_region', $type):
922 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
923 array('context' => 'country')
924 );
925 break;
926
927 case in_array('state_province', $type):
928 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
929 array('context' => 'province')
930 );
931 break;
932
933 default:
934 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
935 break;
936 }
937 }
938 }
939 }
940 elseif (isset($fieldValue) && $fieldValue != '') {
941 //check for custom data
942 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
943 $row[$field . $relationField] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID,
944 $relationQuery[$field]->_options
945 );
946 }
6a488035
TO
947 else {
948 //normal relationship fields
949 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
950 switch ($relationField) {
951 case 'country':
952 case 'world_region':
953 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
954 break;
955
956 case 'state_province':
957 $row[$field . $relationField] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
958 break;
959
960 default:
961 $row[$field . $relationField] = $fieldValue;
962 break;
963 }
964 }
965 }
966 else {
967 // if relation field is empty or null
968 $row[$field . $relationField] = '';
969 }
970 }
971 }
972 elseif (isset($fieldValue) &&
973 $fieldValue != ''
974 ) {
975 //check for custom data
976 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
977 $row[$field] = CRM_Core_BAO_CustomField::getDisplayValue($fieldValue, $cfID, $query->_options);
978 }
979 elseif (array_key_exists($field, $multipleSelectFields)) {
980 //option group fixes
981 $paramsNew = array($field => $fieldValue);
982 if ($field == 'test_tutoring') {
983 $name = array($field => array('newName' => $field, 'groupName' => 'test'));
984 // for readers group
985 }
986 elseif (substr($field, 0, 4) == 'cmr_') {
987 $name = array($field => array('newName' => $field, 'groupName' => substr($field, 0, -3)));
988 }
989 else {
990 $name = array($field => array('newName' => $field, 'groupName' => $field));
991 }
992 CRM_Core_OptionGroup::lookupValues($paramsNew, $name, FALSE);
993 $row[$field] = $paramsNew[$field];
994 }
995 elseif (in_array($field, array(
996 'email_greeting', 'postal_greeting', 'addressee'))) {
997 //special case for greeting replacement
998 $fldValue = "{$field}_display";
999 $row[$field] = $dao->$fldValue;
1000 }
1001 else {
1002 //normal fields with a touch of CRM-3157
1003 switch ($field) {
1004 case 'country':
1005 case 'world_region':
1006 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1007 break;
1008
1009 case 'state_province':
1010 $row[$field] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1011 break;
1012
1013 case 'gender':
1014 case 'preferred_communication_method':
1015 case 'preferred_mail_format':
aa62b355 1016 case 'communication_style':
6a488035
TO
1017 $row[$field] = $i18n->crm_translate($fieldValue);
1018 break;
1019
1020 default:
1021 $row[$field] = $fieldValue;
1022 break;
1023 }
1024 }
1025 }
1026 elseif (substr($field, -8) == 'campaign') {
1027 $campIdFld = "{$field}_id";
1028 $row[$field] = CRM_Utils_Array::value($dao->$campIdFld, $allCampaigns, '');
1029 }
d77aba4b
AS
1030 elseif ($selectedPaymentFields && array_key_exists($field, self::componentPaymentFields())) {
1031 $paymentData = CRM_Utils_Array::value($dao->$paymentTableId, $paymentDetails);
1032 $payFieldMapper = array(
1033 'componentPaymentField_total_amount' => 'total_amount',
1034 'componentPaymentField_contribution_status' => 'contribution_status',
1035 'componentPaymentField_payment_instrument' => 'pay_instru',
1036 'componentPaymentField_transaction_id' => 'trxn_id',
1037 'componentPaymentField_received_date' => 'receive_date',
1038 );
1039 $row[$field] = CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
1040 }
6a488035
TO
1041 else {
1042 // if field is empty or null
1043 $row[$field] = '';
1044 }
1045 }
1046
1047 // add payment headers if required
1048 if ($addPaymentHeader && $paymentFields) {
1049 $headerRows = array_merge($headerRows, $paymentHeaders);
1050 foreach (array_keys($paymentHeaders) as $paymentHdr) {
1051 self::sqlColumnDefn($query, $sqlColumns, $paymentHdr);
1052 }
6a488035
TO
1053 }
1054
1055 if ($setHeader) {
1056 $exportTempTable = self::createTempTable($sqlColumns);
1057 }
1058
1059 //build header only once
1060 $setHeader = FALSE;
1061
e026db3c 1062 // If specific payment fields have been selected for export, payment
545285b8 1063 // data will already be in $row. Otherwise, add payment related
e026db3c 1064 // information, if appropriate.
fc33177b 1065 if ($addPaymentHeader) {
1066 if (!$selectedPaymentFields) {
1067 if ($paymentFields) {
1068 $paymentData = CRM_Utils_Array::value($row[$paymentTableId], $paymentDetails);
1069 if (!is_array($paymentData) || empty($paymentData)) {
1070 $paymentData = $nullContributionDetails;
1071 }
1072 $row = array_merge($row, $paymentData);
1073 }
1074 elseif (!empty($paymentDetails)) {
1075 $row = array_merge($row, $nullContributionDetails);
e026db3c 1076 }
e026db3c 1077 }
6a488035 1078 }
6a488035 1079 //remove organization name for individuals if it is set for current employer
a7488080 1080 if (!empty($row['contact_type']) &&
6a488035
TO
1081 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
1082 ) {
1083 $row['organization_name'] = '';
1084 }
1085
1086 // add component info
1087 // write the row to a file
1088 $componentDetails[] = $row;
1089
1090 // output every $tempRowCount rows
1091 if ($count % $tempRowCount == 0) {
1092 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1093 $componentDetails = array();
1094 }
1095 }
1096 $dao->free();
1097 $offset += $rowCount;
1098 }
1099
1100 if ($exportTempTable) {
1101 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
1102
1103 // do merge same address and merge same household processing
1104 if ($mergeSameAddress) {
1105 self::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
1106 }
1107
1108 // merge the records if they have corresponding households
1109 if ($mergeSameHousehold) {
1110 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyMOH);
1111 self::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, $relationKeyHOH);
1112 }
1113
1114 // fix the headers for rows with relationship type
1115 if (!empty($relName)) {
1116 self::manipulateHeaderRows($headerRows, $contactRelationshipTypes);
1117 }
1118
1119 // if postalMailing option is checked, exclude contacts who are deceased, have
1120 // "Do not mail" privacy setting, or have no street address
1121 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
1122 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
1123 ) {
1124 self::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1125 }
1126
1127 // call export hook
1128 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1129
1130 // now write the CSV file
1131 self::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
1132
1133 // delete the export temp table and component table
1134 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1135 CRM_Core_DAO::executeQuery($sql);
1136
1137 CRM_Utils_System::civiExit();
1138 }
1139 else {
1140 CRM_Core_Error::fatal(ts('No records to export'));
1141 }
1142 }
1143
1144 /**
1145 * name of the export file based on mode
1146 *
1147 * @param string $output type of output
1148 * @param int $mode export mode
1149 *
1150 * @return string name of the file
1151 */
25acfd6b 1152 static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select::CONTACT_EXPORT) {
6a488035
TO
1153 switch ($mode) {
1154 case CRM_Export_Form_Select::CONTACT_EXPORT:
1155 return ts('CiviCRM Contact Search');
1156
1157 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
1158 return ts('CiviCRM Contribution Search');
1159
1160 case CRM_Export_Form_Select::MEMBER_EXPORT:
1161 return ts('CiviCRM Member Search');
1162
1163 case CRM_Export_Form_Select::EVENT_EXPORT:
1164 return ts('CiviCRM Participant Search');
1165
1166 case CRM_Export_Form_Select::PLEDGE_EXPORT:
1167 return ts('CiviCRM Pledge Search');
1168
1169 case CRM_Export_Form_Select::CASE_EXPORT:
1170 return ts('CiviCRM Case Search');
1171
1172 case CRM_Export_Form_Select::GRANT_EXPORT:
1173 return ts('CiviCRM Grant Search');
1174
1175 case CRM_Export_Form_Select::ACTIVITY_EXPORT:
1176 return ts('CiviCRM Activity Search');
1177 }
1178 }
1179
1180 /**
1181 * Function to handle import error file creation.
1182 *
1183 */
c27ca2c8 1184 static function invoke() {
6a488035
TO
1185 $type = CRM_Utils_Request::retrieve('type', 'Positive', CRM_Core_DAO::$_nullObject);
1186 $parserName = CRM_Utils_Request::retrieve('parser', 'String', CRM_Core_DAO::$_nullObject);
1187 if (empty($parserName) || empty($type)) {
1188 return;
1189 }
1190
1191 // clean and ensure parserName is a valid string
1192 $parserName = CRM_Utils_String::munge($parserName);
1193 $parserClass = explode('_', $parserName);
1194
1195 // make sure parserClass is in the CRM namespace and
1196 // at least 3 levels deep
1197 if ($parserClass[0] == 'CRM' &&
1198 count($parserClass) >= 3
1199 ) {
1200 require_once (str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php");
1201 // ensure the functions exists
1202 if (method_exists($parserName, 'errorFileName') &&
1203 method_exists($parserName, 'saveFileName')
1204 ) {
1205 $errorFileName = $parserName::errorFileName($type);
1206 $saveFileName = $parserName::saveFileName($type);
1207 if (!empty($errorFileName) && !empty($saveFileName)) {
1208 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
1209 header('Content-Description: File Transfer');
1210 header('Content-Type: text/csv');
1211 header('Content-Length: ' . filesize($errorFileName));
1212 header('Content-Disposition: attachment; filename=' . $saveFileName);
1213
1214 readfile($errorFileName);
1215 }
1216 }
1217 }
1218 CRM_Utils_System::civiExit();
1219 }
1220
c27ca2c8 1221 static function exportCustom($customSearchClass, $formValues, $order) {
6a488035
TO
1222 $ext = CRM_Extension_System::singleton()->getMapper();
1223 if (!$ext->isExtensionClass($customSearchClass)) {
1224 require_once (str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php');
1225 }
1226 else {
1227 require_once ($ext->classToPath($customSearchClass));
1228 }
1229 $search = new $customSearchClass($formValues);
1230
1231 $includeContactIDs = FALSE;
1232 if ($formValues['radio_ts'] == 'ts_sel') {
1233 $includeContactIDs = TRUE;
1234 }
1235
1236 $sql = $search->all(0, 0, $order, $includeContactIDs);
1237
1238 $columns = $search->columns();
1239
1240 $header = array_keys($columns);
1241 $fields = array_values($columns);
1242
1243 $rows = array();
1244 $dao = CRM_Core_DAO::executeQuery($sql);
1245 $alterRow = FALSE;
1246 if (method_exists($search, 'alterRow')) {
1247 $alterRow = TRUE;
1248 }
1249 while ($dao->fetch()) {
1250 $row = array();
1251
1252 foreach ($fields as $field) {
1253 $row[$field] = $dao->$field;
1254 }
1255 if ($alterRow) {
1256 $search->alterRow($row);
1257 }
1258 $rows[] = $row;
1259 }
1260
1261 CRM_Core_Report_Excel::writeCSVFile(self::getExportFileName(), $header, $rows);
1262 CRM_Utils_System::civiExit();
1263 }
1264
1265 static function sqlColumnDefn(&$query, &$sqlColumns, $field) {
0944820d 1266 if (substr($field, -4) == '_a_b' || substr($field, -4) == '_b_a') {
6a488035
TO
1267 return;
1268 }
1269
1270 $fieldName = CRM_Utils_String::munge(strtolower($field), '_', 64);
1271 if ($fieldName == 'id') {
1272 $fieldName = 'civicrm_primary_id';
1273 }
1274
0944820d
DL
1275 // early exit for master_id, CRM-12100
1276 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
1277 if ($fieldName == 'master_id') {
1278 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
1279 return;
1280 }
1281
6a488035
TO
1282 // set the sql columns
1283 if (isset($query->_fields[$field]['type'])) {
1284 switch ($query->_fields[$field]['type']) {
1285 case CRM_Utils_Type::T_INT:
6a488035
TO
1286 case CRM_Utils_Type::T_BOOLEAN:
1287 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1288 break;
1289
1290 case CRM_Utils_Type::T_STRING:
1291 if (isset($query->_fields[$field]['maxlength'])) {
1292 $sqlColumns[$fieldName] = "$fieldName varchar({$query->_fields[$field]['maxlength']})";
1293 }
1294 else {
1295 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1296 }
1297 break;
1298
1299 case CRM_Utils_Type::T_TEXT:
1300 case CRM_Utils_Type::T_LONGTEXT:
1301 case CRM_Utils_Type::T_BLOB:
1302 case CRM_Utils_Type::T_MEDIUMBLOB:
1303 $sqlColumns[$fieldName] = "$fieldName longtext";
1304 break;
1305
1306 case CRM_Utils_Type::T_FLOAT:
1307 case CRM_Utils_Type::T_ENUM:
1308 case CRM_Utils_Type::T_DATE:
1309 case CRM_Utils_Type::T_TIME:
1310 case CRM_Utils_Type::T_TIMESTAMP:
1311 case CRM_Utils_Type::T_MONEY:
1312 case CRM_Utils_Type::T_EMAIL:
1313 case CRM_Utils_Type::T_URL:
1314 case CRM_Utils_Type::T_CCNUM:
1315 default:
1316 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
1317 break;
1318 }
1319 }
1320 else {
1321 if (substr($fieldName, -3, 3) == '_id') {
1338f0b1
DL
1322 // for trxn_id and its variants use a longer buffer
1323 // to accomodate different systems - CRM-13739
1324 static $notRealIDFields = NULL;
1325 if ($notRealIDFields == NULL) {
1326 $notRealIDFields = array( 'trxn_id', 'componentpaymentfield_transaction_id' );
1327 }
1328
1329 if (in_array($fieldName, $notRealIDFields)) {
1330 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1331 }
1332 else {
1333 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
1334 }
6a488035
TO
1335 }
1336 else {
1337 $changeFields = array(
1338 'groups',
1339 'tags',
1340 'notes'
1341 );
1342
1343 if (in_array($fieldName, $changeFields)) {
1344 $sqlColumns[$fieldName] = "$fieldName text";
1345 }
1346 else {
1347 // set the sql columns for custom data
1348 if (isset($query->_fields[$field]['data_type'])) {
1349
1350 switch ($query->_fields[$field]['data_type']) {
1351 case 'Country':
1352 case 'StateProvince':
1353 case 'Link':
1354 case 'String':
1355 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
1356 break;
1357
1358 case 'Memo':
1359 $sqlColumns[$fieldName] = "$fieldName text";
1360 break;
1361
1362 default:
1363 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1364 break;
1365 }
1366 }
1367 else {
1368 $sqlColumns[$fieldName] = "$fieldName varchar(64)";
1369 }
1370 }
1371 }
1372 }
1373 }
1374
1375 static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
1376 if (empty($details)) {
1377 return;
1378 }
1379
1380 $sql = "
1381SELECT max(id)
1382FROM $tableName
1383";
1384
1385 $id = CRM_Core_DAO::singleValueQuery($sql);
1386 if (!$id) {
1387 $id = 0;
1388 }
1389
1390 $sqlClause = array();
1391
1392 foreach ($details as $dontCare => $row) {
1393 $id++;
1394 $valueString = array($id);
1395 foreach ($row as $dontCare => $value) {
1396 if (empty($value)) {
1397 $valueString[] = "''";
1398 }
1399 else {
1400 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
1401 }
1402 }
1403 $sqlClause[] = '(' . implode(',', $valueString) . ')';
1404 }
1405
1406 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
1407
1408 $sqlValueString = implode(",\n", $sqlClause);
1409
1410 $sql = "
1411INSERT INTO $tableName $sqlColumnString
1412VALUES $sqlValueString
1413";
1414
1415 CRM_Core_DAO::executeQuery($sql);
1416 }
1417
1418 static function createTempTable(&$sqlColumns) {
1419 //creating a temporary table for the search result that need be exported
1420 $exportTempTable = CRM_Core_DAO::createTempTableName('civicrm_export', TRUE);
1421
1422 // also create the sql table
1423 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
1424 CRM_Core_DAO::executeQuery($sql);
1425
1426 $sql = "
1427CREATE TABLE {$exportTempTable} (
1428 id int unsigned NOT NULL AUTO_INCREMENT,
1429";
1430 $sql .= implode(",\n", array_values($sqlColumns));
1431
1432 $sql .= ",
1433 PRIMARY KEY ( id )
1434";
1435 // add indexes for street_address and household_name if present
1436 $addIndices = array(
1437 'street_address',
1438 'household_name',
1439 'civicrm_primary_id',
1440 );
1441
1442 foreach ($addIndices as $index) {
1443 if (isset($sqlColumns[$index])) {
1444 $sql .= ",
1445 INDEX index_{$index}( $index )
1446";
1447 }
1448 }
1449
1450 $sql .= "
1451) ENGINE=MyISAM DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1452";
1453
1454 CRM_Core_DAO::executeQuery($sql);
1455 return $exportTempTable;
1456 }
1457
1458 static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1459 // check if any records are present based on if they have used shared address feature,
1460 // and not based on if city / state .. matches.
1461 $sql = "
1462SELECT r1.id as copy_id,
1463 r1.civicrm_primary_id as copy_contact_id,
1464 r1.addressee as copy_addressee,
1465 r1.addressee_id as copy_addressee_id,
1466 r1.postal_greeting as copy_postal_greeting,
1467 r1.postal_greeting_id as copy_postal_greeting_id,
1468 r2.id as master_id,
1469 r2.civicrm_primary_id as master_contact_id,
1470 r2.postal_greeting as master_postal_greeting,
1471 r2.postal_greeting_id as master_postal_greeting_id,
1472 r2.addressee as master_addressee,
1473 r2.addressee_id as master_addressee_id
1474FROM $tableName r1
1475INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1476INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1477ORDER BY r1.id";
1478 $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE);
1479
1480 // find all the records that have the same street address BUT not in a household
1481 // require match on city and state as well
1482 $sql = "
1483SELECT r1.id as master_id,
1484 r1.civicrm_primary_id as master_contact_id,
1485 r1.postal_greeting as master_postal_greeting,
1486 r1.postal_greeting_id as master_postal_greeting_id,
1487 r1.addressee as master_addressee,
1488 r1.addressee_id as master_addressee_id,
1489 r2.id as copy_id,
1490 r2.civicrm_primary_id as copy_contact_id,
1491 r2.postal_greeting as copy_postal_greeting,
1492 r2.postal_greeting_id as copy_postal_greeting_id,
1493 r2.addressee as copy_addressee,
1494 r2.addressee_id as copy_addressee_id
1495FROM $tableName r1
1496LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1497 r1.city = r2.city AND
1498 r1.state_province_id = r2.state_province_id )
1499WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1500AND ( r2.household_name IS NULL OR r2.household_name = '' )
1501AND ( r1.street_address != '' )
1502AND r2.id > r1.id
1503ORDER BY r1.id
1504";
1505 $merge = self::_buildMasterCopyArray($sql, $exportParams);
1506
1507 // unset ids from $merge already present in $linkedMerge
1508 foreach ($linkedMerge as $masterID => $values) {
1509 $keys = array($masterID);
1510 $keys = array_merge($keys, array_keys($values['copy']));
1511 foreach ($merge as $mid => $vals) {
1512 if (in_array($mid, $keys)) {
1513 unset($merge[$mid]);
1514 }
1515 else {
1516 foreach ($values['copy'] as $copyId) {
1517 if (in_array($copyId, $keys)) {
1518 unset($merge[$mid]['copy'][$copyId]);
1519 }
1520 }
1521 }
1522 }
1523 }
1524 $merge = $merge + $linkedMerge;
1525
1526 foreach ($merge as $masterID => $values) {
1527 $sql = "
1528UPDATE $tableName
1529SET addressee = %1, postal_greeting = %2, email_greeting = %3
1530WHERE id = %4
1531";
1532 $params = array(1 => array($values['addressee'], 'String'),
1533 2 => array($values['postalGreeting'], 'String'),
1534 3 => array($values['emailGreeting'], 'String'),
1535 4 => array($masterID, 'Integer'),
1536 );
1537 CRM_Core_DAO::executeQuery($sql, $params);
1538
1539 // delete all copies
1540 $deleteIDs = array_keys($values['copy']);
1541 $deleteIDString = implode(',', $deleteIDs);
1542 $sql = "
1543DELETE FROM $tableName
1544WHERE id IN ( $deleteIDString )
1545";
1546 CRM_Core_DAO::executeQuery($sql);
1547 }
1548
1549 // unset temporary columns that were added for postal mailing format
1550 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1551 $unsetKeys = array_keys($sqlColumns);
1552 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1553 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1554 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1555 }
1556 }
1557 }
1558 }
1559
1560 static function _replaceMergeTokens($contactId, $exportParams) {
1561 $greetings = array();
1562 $contact = NULL;
1563
1564 $greetingFields = array(
1565 'postal_greeting',
1566 'addressee',
1567 );
1568 foreach ($greetingFields as $greeting) {
a7488080 1569 if (!empty($exportParams[$greeting])) {
6a488035
TO
1570 $greetingLabel = $exportParams[$greeting];
1571 if (empty($contact)) {
1572 $values = array(
1573 'id' => $contactId,
1574 'version' => 3,
1575 );
1576 $contact = civicrm_api('contact', 'get', $values);
1577
a7488080 1578 if (!empty($contact['is_error'])) {
6a488035
TO
1579 return $greetings;
1580 }
1581 $contact = $contact['values'][$contact['id']];
1582 }
1583
1584 $tokens = array('contact' => $greetingLabel);
1585 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1586 }
1587 }
1588 return $greetings;
1589 }
1590
1591 /**
1592 * The function unsets static part of the string, if token is the dynamic part.
1593 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1594 * i.e 'Hello Alan' => converted to => 'Alan'
1595 *
1596 */
1597 static function _trimNonTokens(&$parsedString, $defaultGreeting,
1598 $addressMergeGreetings, $greetingType = 'postal_greeting'
1599 ) {
a7488080 1600 if (!empty($addressMergeGreetings[$greetingType])) {
6a488035
TO
1601 $greetingLabel = $addressMergeGreetings[$greetingType];
1602 }
1603 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
1604
1605 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1606 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1607 foreach ($stringsToBeReplaced as $key => $string) {
1608 // to keep one space
1609 $stringsToBeReplaced[$key] = ltrim($string);
1610 }
1611 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1612
1613 return $parsedString;
1614 }
1615
1616 static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1617 static $contactGreetingTokens = array();
1618
1619 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
1620 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
1621
1622 $merge = $parents = array();
1623 $dao = CRM_Core_DAO::executeQuery($sql);
1624
1625 while ($dao->fetch()) {
1626 $masterID = $dao->master_id;
1627 $copyID = $dao->copy_id;
1628 $masterPostalGreeting = $dao->master_postal_greeting;
1629 $masterAddressee = $dao->master_addressee;
1630 $copyAddressee = $dao->copy_addressee;
1631
1632 if (!$sharedAddress) {
1633 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
1634 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
1635 }
1636 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1637 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
1638 );
1639 $masterAddressee = CRM_Utils_Array::value('addressee',
1640 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
1641 );
1642
1643 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
1644 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
1645 }
1646 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
1647 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
1648 );
1649 $copyAddressee = CRM_Utils_Array::value('addressee',
1650 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
1651 );
1652 }
1653
1654 if (!isset($merge[$masterID])) {
1655 // check if this is an intermediate child
1656 // this happens if there are 3 or more matches a,b, c
1657 // the above query will return a, b / a, c / b, c
1658 // we might be doing a bit more work, but for now its ok, unless someone
1659 // knows how to fix the query above
1660 if (isset($parents[$masterID])) {
1661 $masterID = $parents[$masterID];
1662 }
1663 else {
1664 $merge[$masterID] = array(
1665 'addressee' => $masterAddressee,
1666 'copy' => array(),
1667 'postalGreeting' => $masterPostalGreeting,
1668 );
1669 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1670 }
1671 }
1672 $parents[$copyID] = $masterID;
1673
1674 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1675
a7488080 1676 if (!empty($exportParams['postal_greeting_other']) &&
6a488035
TO
1677 count($merge[$masterID]['copy']) >= 1
1678 ) {
1679 // use static greetings specified if no of contacts > 2
1680 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1681 }
1682 elseif ($copyPostalGreeting) {
1683 self::_trimNonTokens($copyPostalGreeting,
1684 $postalOptions[$dao->copy_postal_greeting_id],
1685 $exportParams
1686 );
1687 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1688 // if there happens to be a duplicate, remove it
1689 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1690 }
1691
a7488080 1692 if (!empty($exportParams['addressee_other']) &&
6a488035
TO
1693 count($merge[$masterID]['copy']) >= 1
1694 ) {
1695 // use static greetings specified if no of contacts > 2
1696 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1697 }
1698 elseif ($copyAddressee) {
1699 self::_trimNonTokens($copyAddressee,
1700 $addresseeOptions[$dao->copy_addressee_id],
1701 $exportParams, 'addressee'
1702 );
1703 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1704 }
1705 }
1706 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1707 }
1708
1709 return $merge;
1710 }
1711
1712 /**
1713 * Function to merge household record into the individual record
1714 * if exists
1715 *
1716 * @param string $exportTempTable temporary temp table that stores the records
1717 * @param array $headerRows array of headers for the export file
1718 * @param array $sqlColumns array of names of the table columns of the temp table
1719 * @param string $prefix name of the relationship type that is prefixed to the table columns
1720 */
1721 static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1722 $prefixColumn = $prefix . '_';
1723 $allKeys = array_keys($sqlColumns);
1724 $replaced = array();
1725 $headerRows = array_values($headerRows);
1726
1727 // name map of the non standard fields in header rows & sql columns
1728 $mappingFields = array(
1729 'civicrm_primary_id' => 'id',
1730 'contact_source' => 'source',
1731 'current_employer_id' => 'employer_id',
1732 'contact_is_deleted' => 'is_deleted',
1733 'name' => 'address_name',
1734 'provider_id' => 'im_service_provider',
1735 'phone_type_id' => 'phone_type'
1736 );
1737
1738 //figure out which columns are to be replaced by which ones
1739 foreach ($sqlColumns as $columnNames => $dontCare) {
1740 if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) {
1741 $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64);
1742 }
1743 else {
1744 $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64);
1745
a7488080 1746 if (!empty($sqlColumns[$householdColName])) {
6a488035
TO
1747 $replaced[$columnNames] = $householdColName;
1748 }
1749 }
1750 }
1751 $query = "UPDATE $exportTempTable SET ";
1752
1753 $clause = array();
1754 foreach ($replaced as $from => $to) {
1755 $clause[] = "$from = $to ";
1756 unset($sqlColumns[$to]);
1757 if ($key = CRM_Utils_Array::key($to, $allKeys)) {
1758 unset($headerRows[$key]);
1759 }
1760 }
1761 $query .= implode(",\n", $clause);
1762 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1763
1764 CRM_Core_DAO::executeQuery($query);
1765
1766 //drop the table columns that store redundant household info
1767 $dropQuery = "ALTER TABLE $exportTempTable ";
1768 foreach ($replaced as $householdColumns) {
1769 $dropClause[] = " DROP $householdColumns ";
1770 }
1771 $dropQuery .= implode(",\n", $dropClause);
1772
1773 CRM_Core_DAO::executeQuery($dropQuery);
1774
1775 // also drop the temp table if exists
1776 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1777 CRM_Core_DAO::executeQuery($sql);
1778
1779 // clean up duplicate records
1780 $query = "
1781CREATE TABLE {$exportTempTable}_temp SELECT *
1782FROM {$exportTempTable}
1783GROUP BY civicrm_primary_id ";
1784
1785 CRM_Core_DAO::executeQuery($query);
1786
1787 $query = "DROP TABLE $exportTempTable";
1788 CRM_Core_DAO::executeQuery($query);
1789
1790 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1791 CRM_Core_DAO::executeQuery($query);
1792 }
1793
1794 static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = null, $batchItems = '') {
1795 $writeHeader = TRUE;
1796 $offset = 0;
1797 $limit = self::EXPORT_ROW_COUNT;
1798
1799 $query = "SELECT * FROM $exportTempTable";
1800
1801 while (1) {
1802 $limitQuery = $query . "
1803LIMIT $offset, $limit
1804";
1805 $dao = CRM_Core_DAO::executeQuery($limitQuery);
1806
1807 if ($dao->N <= 0) {
1808 break;
1809 }
1810
1811 $componentDetails = array();
1812 while ($dao->fetch()) {
1813 $row = array();
1814
1815 foreach ($sqlColumns as $column => $dontCare) {
1816 $row[$column] = $dao->$column;
1817 }
1818 $componentDetails[] = $row;
1819 }
1820 if ( $exportMode == 'financial' ) {
1821 $getExportFileName = 'CiviCRM Contribution Search';
1822 }
1823 else {
1824 $getExportFileName =self::getExportFileName( 'csv', $exportMode );
1825 }
1826 $csvRows = CRM_Core_Report_Excel::writeCSVFile( $getExportFileName,
1827 $headerRows,
1828 $componentDetails,
1829 null,
1830 $writeHeader,
1831 $saveFile );
1832
1833 if ($saveFile && !empty($csvRows)) {
1834 $batchItems .= $csvRows;
1835 }
1836
1837 $writeHeader = false;
1838 $offset += $limit;
1839 }
1840 }
1841
1842 /**
1843 * Function to manipulate header rows for relationship fields
1844 *
1845 */
1571c7e7 1846 public static function manipulateHeaderRows(&$headerRows, $contactRelationshipTypes) {
6a488035
TO
1847 foreach ($headerRows as & $header) {
1848 $split = explode('-', $header);
1849 if ($relationTypeName = CRM_Utils_Array::value($split[0], $contactRelationshipTypes)) {
1850 $split[0] = $relationTypeName;
1851 $header = implode('-', $split);
1852 }
1853 }
1854 }
1855
1856 /**
1857 * Function to exclude contacts who are deceased, have "Do not mail" privacy setting,
1858 * or have no street address
1859 *
1860 */
c27ca2c8 1861 static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
6a488035
TO
1862 $whereClause = array();
1863
1864 if (array_key_exists('is_deceased', $sqlColumns)) {
1865 $whereClause[] = 'is_deceased = 1';
1866 }
1867
1868 if (array_key_exists('do_not_mail', $sqlColumns)) {
1869 $whereClause[] = 'do_not_mail = 1';
1870 }
1871
1872 if (array_key_exists('street_address', $sqlColumns)) {
1873 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1874
1875 // check for supplemental_address_1
1876 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1877 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1878 'address_options', TRUE, NULL, TRUE
1879 );
a7488080 1880 if (!empty($addressOptions['supplemental_address_1'])) {
6a488035
TO
1881 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1882 // enclose it again, since we are doing an AND in between a set of ORs
1883 $addressWhereClause = "( $addressWhereClause )";
1884 }
1885 }
1886
1887 $whereClause[] = $addressWhereClause;
1888 }
1889
1890 if (!empty($whereClause)) {
1891 $whereClause = implode(' OR ', $whereClause);
1892 $query = "
1893DELETE
1894FROM $exportTempTable
1895WHERE {$whereClause}";
1896 CRM_Core_DAO::singleValueQuery($query);
1897 }
1898
1899 // unset temporary columns that were added for postal mailing format
1900 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1901 $unsetKeys = array_keys($sqlColumns);
1902 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1903 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1904 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1905 }
1906 }
1907 }
1908 }
d77aba4b
AS
1909
1910 /**
1911 * Build componentPayment fields.
1912 */
1913 static function componentPaymentFields() {
1914 static $componentPaymentFields;
1915 if (!isset( $componentPaymentFields)) {
1916 $componentPaymentFields = array(
1917 'componentPaymentField_total_amount' => ts('Total Amount'),
1918 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1919 'componentPaymentField_received_date' => ts('Received Date'),
1920 'componentPaymentField_payment_instrument' => ts('Payment Instrument'),
1921 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1922 );
1923 }
1924 return $componentPaymentFields;
1925 }
6a488035
TO
1926}
1927