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