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