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