Merge pull request #13019 from seamuslee001/lab_core_481
[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 1126 $replaced = array();
6a488035
TO
1127
1128 // name map of the non standard fields in header rows & sql columns
1129 $mappingFields = array(
1130 'civicrm_primary_id' => 'id',
6a488035 1131 'provider_id' => 'im_service_provider',
21dfd5f5 1132 'phone_type_id' => 'phone_type',
6a488035
TO
1133 );
1134
1135 //figure out which columns are to be replaced by which ones
1136 foreach ($sqlColumns as $columnNames => $dontCare) {
1137 if ($rep = CRM_Utils_Array::value($columnNames, $mappingFields)) {
1138 $replaced[$columnNames] = CRM_Utils_String::munge($prefixColumn . $rep, '_', 64);
1139 }
1140 else {
1141 $householdColName = CRM_Utils_String::munge($prefixColumn . $columnNames, '_', 64);
1142
a7488080 1143 if (!empty($sqlColumns[$householdColName])) {
6a488035
TO
1144 $replaced[$columnNames] = $householdColName;
1145 }
1146 }
1147 }
1148 $query = "UPDATE $exportTempTable SET ";
1149
1150 $clause = array();
1151 foreach ($replaced as $from => $to) {
1152 $clause[] = "$from = $to ";
1153 unset($sqlColumns[$to]);
6a488035
TO
1154 }
1155 $query .= implode(",\n", $clause);
1156 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1157
1158 CRM_Core_DAO::executeQuery($query);
1159
1160 //drop the table columns that store redundant household info
1161 $dropQuery = "ALTER TABLE $exportTempTable ";
1162 foreach ($replaced as $householdColumns) {
1163 $dropClause[] = " DROP $householdColumns ";
1164 }
1165 $dropQuery .= implode(",\n", $dropClause);
1166
1167 CRM_Core_DAO::executeQuery($dropQuery);
1168
1169 // also drop the temp table if exists
1170 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1171 CRM_Core_DAO::executeQuery($sql);
1172
1173 // clean up duplicate records
1174 $query = "
1175CREATE TABLE {$exportTempTable}_temp SELECT *
1176FROM {$exportTempTable}
1177GROUP BY civicrm_primary_id ";
1178
1179 CRM_Core_DAO::executeQuery($query);
1180
1181 $query = "DROP TABLE $exportTempTable";
1182 CRM_Core_DAO::executeQuery($query);
1183
1184 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1185 CRM_Core_DAO::executeQuery($query);
1186 }
1187
e0ef6999
EM
1188 /**
1189 * @param $exportTempTable
1190 * @param $headerRows
1191 * @param $sqlColumns
70107611 1192 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999 1193 */
70107611 1194 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor) {
1195 $exportMode = $processor->getExportMode();
6a488035 1196 $writeHeader = TRUE;
97f6897c
TO
1197 $offset = 0;
1198 $limit = self::EXPORT_ROW_COUNT;
6a488035
TO
1199
1200 $query = "SELECT * FROM $exportTempTable";
1201
1202 while (1) {
1203 $limitQuery = $query . "
1204LIMIT $offset, $limit
1205";
1206 $dao = CRM_Core_DAO::executeQuery($limitQuery);
1207
1208 if ($dao->N <= 0) {
1209 break;
1210 }
1211
1212 $componentDetails = array();
1213 while ($dao->fetch()) {
1214 $row = array();
1215
1216 foreach ($sqlColumns as $column => $dontCare) {
1217 $row[$column] = $dao->$column;
1218 }
1219 $componentDetails[] = $row;
1220 }
29034a98 1221 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
6a488035
TO
1222 $headerRows,
1223 $componentDetails,
97f6897c 1224 NULL,
70107611 1225 $writeHeader
1226 );
6a488035 1227
97f6897c 1228 $writeHeader = FALSE;
6a488035
TO
1229 $offset += $limit;
1230 }
1231 }
1232
1233 /**
fe482240 1234 * Manipulate header rows for relationship fields.
ca87146b
EM
1235 *
1236 * @param $headerRows
6a488035 1237 */
2593f7dc 1238 public static function manipulateHeaderRows(&$headerRows) {
6a488035
TO
1239 foreach ($headerRows as & $header) {
1240 $split = explode('-', $header);
2593f7dc 1241 if ($relationTypeName = CRM_Utils_Array::value($split[0], self::$relationshipTypes)) {
6a488035
TO
1242 $split[0] = $relationTypeName;
1243 $header = implode('-', $split);
1244 }
1245 }
1246 }
1247
1248 /**
100fef9d 1249 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
6a488035 1250 * or have no street address
ca87146b
EM
1251 * @param $exportTempTable
1252 * @param $headerRows
1253 * @param $sqlColumns
1254 * @param $exportParams
6a488035 1255 */
00be9182 1256 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
6a488035
TO
1257 $whereClause = array();
1258
1259 if (array_key_exists('is_deceased', $sqlColumns)) {
1260 $whereClause[] = 'is_deceased = 1';
1261 }
1262
1263 if (array_key_exists('do_not_mail', $sqlColumns)) {
1264 $whereClause[] = 'do_not_mail = 1';
1265 }
1266
1267 if (array_key_exists('street_address', $sqlColumns)) {
1268 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1269
1270 // check for supplemental_address_1
1271 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1272 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
1273 'address_options', TRUE, NULL, TRUE
1274 );
a7488080 1275 if (!empty($addressOptions['supplemental_address_1'])) {
6a488035
TO
1276 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1277 // enclose it again, since we are doing an AND in between a set of ORs
1278 $addressWhereClause = "( $addressWhereClause )";
1279 }
1280 }
1281
1282 $whereClause[] = $addressWhereClause;
1283 }
1284
1285 if (!empty($whereClause)) {
1286 $whereClause = implode(' OR ', $whereClause);
1287 $query = "
1288DELETE
1289FROM $exportTempTable
1290WHERE {$whereClause}";
1291 CRM_Core_DAO::singleValueQuery($query);
1292 }
1293
1294 // unset temporary columns that were added for postal mailing format
1295 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1296 $unsetKeys = array_keys($sqlColumns);
1297 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1298 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1299 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1300 }
1301 }
1302 }
1303 }
d77aba4b
AS
1304
1305 /**
1306 * Build componentPayment fields.
1307 */
00be9182 1308 public static function componentPaymentFields() {
d77aba4b 1309 static $componentPaymentFields;
97f6897c 1310 if (!isset($componentPaymentFields)) {
d77aba4b 1311 $componentPaymentFields = array(
97f6897c 1312 'componentPaymentField_total_amount' => ts('Total Amount'),
d77aba4b 1313 'componentPaymentField_contribution_status' => ts('Contribution Status'),
7bc6b5bb 1314 'componentPaymentField_received_date' => ts('Date Received'),
536f0e02 1315 'componentPaymentField_payment_instrument' => ts('Payment Method'),
97f6897c 1316 'componentPaymentField_transaction_id' => ts('Transaction ID'),
d77aba4b
AS
1317 );
1318 }
1319 return $componentPaymentFields;
1320 }
96025800 1321
12a36993 1322 /**
1323 * Set the definition for the header rows and sql columns based on the field to output.
1324 *
1325 * @param string $field
1326 * @param array $headerRows
adabfa40 1327 * @param \CRM_Export_BAO_ExportProcessor $processor
c66a5741 1328 *
12a36993 1329 * @return array
1330 */
cf1b70b7 1331 public static function setHeaderRows($field, $headerRows, $processor) {
12a36993 1332
adabfa40 1333 $queryFields = $processor->getQueryFields();
219c47d6 1334 if (substr($field, -11) == 'campaign_id') {
1335 // @todo - set this correctly in the xml rather than here.
12a36993 1336 $headerRows[] = ts('Campaign ID');
1337 }
b7db6051 1338 elseif ($processor->isMergeSameHousehold() && $field === 'id') {
1339 $headerRows[] = ts('Household ID');
1340 }
3110c417 1341 elseif (isset($queryFields[$field]['title'])) {
1342 $headerRows[] = $queryFields[$field]['title'];
12a36993 1343 }
12a36993 1344 elseif ($field == 'provider_id') {
219c47d6 1345 // @todo - set this correctly in the xml rather than here.
12a36993 1346 $headerRows[] = ts('IM Service Provider');
1347 }
c66a5741 1348 elseif ($processor->isExportPaymentFields() && array_key_exists($field, self::componentPaymentFields())) {
12a36993 1349 $headerRows[] = CRM_Utils_Array::value($field, self::componentPaymentFields());
1350 }
1351 else {
1352 $headerRows[] = $field;
1353 }
1354
cf1b70b7 1355 return $headerRows;
12a36993 1356 }
1357
1358 /**
1359 * Get the various arrays that we use to structure our output.
1360 *
1361 * The extraction of these has been moved to a separate function for clarity and so that
1362 * tests can be added - in particular on the $outputHeaders array.
1363 *
1364 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1365 * as a step on the refactoring path rather than how it should be.
1366 *
1367 * @param array $returnProperties
adabfa40 1368 * @param \CRM_Export_BAO_ExportProcessor $processor
c66a5741 1369 *
12a36993 1370 * @return array
1371 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1372 * alias for the field generated by BAO_Query object.
1373 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1374 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1375 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1376 * I'm too embarassed to discuss here.
1377 * The keys need
1378 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1379 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1380 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1381 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1382 * - a) the function used is more efficient or
1383 * - b) this code is old & outdated. Submit your answers to circular bin or better
1384 * yet find a way to comment them for posterity.
1385 */
2a48e887 1386 public static function getExportStructureArrays($returnProperties, $processor) {
12a36993 1387 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
efc76c0a 1388 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
1389 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
adabfa40 1390 $queryFields = $processor->getQueryFields();
12a36993 1391 foreach ($returnProperties as $key => $value) {
3883f8fb 1392 if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
1393 $outputColumns[$key] = $value;
cf1b70b7 1394 $headerRows = self::setHeaderRows($key, $headerRows, $processor);
1395 self::sqlColumnDefn($processor, $sqlColumns, $key);
3883f8fb 1396 }
1397 elseif ($processor->isRelationshipTypeKey($key)) {
12a36993 1398 $outputColumns[$key] = $value;
3883f8fb 1399 $field = $key;
1400 foreach ($value as $relationField => $relationValue) {
1401 // below block is same as primary block (duplicate)
1402 if (isset($queryFields[$relationField]['title'])) {
1403 if ($queryFields[$relationField]['name'] == 'name') {
1404 $headerName = $field . '-' . $relationField;
1405 }
1406 else {
1407 if ($relationField == 'current_employer') {
1408 $headerName = $field . '-' . 'current_employer';
1409 }
1410 else {
cedeaa5c 1411 $headerName = $field . '-' . $relationField;
3883f8fb 1412 }
1413 }
1414
1415 if (!$processor->isHouseholdMergeRelationshipTypeKey($field)) {
1416 // Do not add to header row if we are only generating for merge reasons.
1417 $headerRows[] = $headerName;
1418 }
1419
1420 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1421 }
1422 elseif ($relationField == 'phone_type_id') {
1423 $headerName = $field . '-' . 'Phone Type';
1424 $headerRows[] = $headerName;
1425 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1426 }
1427 elseif ($relationField == 'provider_id') {
1428 $headerName = $field . '-' . 'Im Service Provider';
1429 $headerRows[] = $headerName;
1430 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1431 }
1432 elseif ($relationField == 'state_province_id') {
1433 $headerName = $field . '-' . 'state_province_id';
1434 $headerRows[] = $headerName;
1435 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1436 }
1437 elseif (is_array($relationValue) && $relationField == 'location') {
1438 // fix header for location type case
1439 foreach ($relationValue as $ltype => $val) {
1440 foreach (array_keys($val) as $fld) {
1441 $type = explode('-', $fld);
1442
1443 $hdr = "{$ltype}-" . $queryFields[$type[0]]['title'];
1444
1445 if (!empty($type[1])) {
1446 if (CRM_Utils_Array::value(0, $type) == 'phone') {
1447 $hdr .= "-" . CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $type[1]);
1448 }
1449 elseif (CRM_Utils_Array::value(0, $type) == 'im') {
1450 $hdr .= "-" . CRM_Core_PseudoConstant::getLabel('CRM_Core_BAO_IM', 'provider_id', $type[1]);
1451 }
1452 }
1453 $headerName = $field . '-' . $hdr;
1454 $headerRows[] = $headerName;
1455 self::sqlColumnDefn($processor, $sqlColumns, $headerName);
1456 }
1457 }
1458 }
1459 }
1460 self::manipulateHeaderRows($headerRows);
12a36993 1461 }
1462 else {
1463 foreach ($value as $locationType => $locationFields) {
1464 foreach (array_keys($locationFields) as $locationFieldName) {
1465 $type = explode('-', $locationFieldName);
1466
1467 $actualDBFieldName = $type[0];
3110c417 1468 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
12a36993 1469 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
1470
1471 if (!empty($type[1])) {
1472 $daoFieldName .= "-" . $type[1];
1473 if ($actualDBFieldName == 'phone') {
1474 $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $phoneTypes);
1475 }
1476 elseif ($actualDBFieldName == 'im') {
1477 $outputFieldName .= "-" . CRM_Utils_Array::value($type[1], $imProviders);
1478 }
1479 }
1480 if ($type[0] == 'im_provider') {
1481 // Warning: shame inducing hack.
1482 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1483 }
adabfa40 1484 self::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
cf1b70b7 1485 $headerRows = self::setHeaderRows($outputFieldName, $headerRows, $processor);
1486 self::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
12a36993 1487 if ($actualDBFieldName == 'country' || $actualDBFieldName == 'world_region') {
1488 $metadata[$daoFieldName] = array('context' => 'country');
1489 }
1490 if ($actualDBFieldName == 'state_province') {
1491 $metadata[$daoFieldName] = array('context' => 'province');
1492 }
1493 $outputColumns[$daoFieldName] = TRUE;
1494 }
1495 }
1496 }
1497 }
1498 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1499 }
1500
1860fab0 1501 /**
1502 * Get the values of linked household contact.
1503 *
1504 * @param CRM_Core_DAO $relDAO
1505 * @param array $value
1506 * @param string $field
1507 * @param array $row
1508 */
1509 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1510 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
1511 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1512 $i18n = CRM_Core_I18n::singleton();
ce12a9e0 1513 $field = $field . '_';
1514
1860fab0 1515 foreach ($value as $relationField => $relationValue) {
1516 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1517 $fieldValue = $relDAO->$relationField;
1518 if ($relationField == 'phone_type_id') {
1519 $fieldValue = $phoneTypes[$relationValue];
1520 }
1521 elseif ($relationField == 'provider_id') {
1522 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
1523 }
1524 // CRM-13995
1525 elseif (is_object($relDAO) && in_array($relationField, array(
1526 'email_greeting',
1527 'postal_greeting',
1528 'addressee',
1529 ))
1530 ) {
1531 //special case for greeting replacement
1532 $fldValue = "{$relationField}_display";
1533 $fieldValue = $relDAO->$fldValue;
1534 }
1535 }
1536 elseif (is_object($relDAO) && $relationField == 'state_province') {
1537 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
1538 }
1539 elseif (is_object($relDAO) && $relationField == 'country') {
1540 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
1541 }
1542 else {
1543 $fieldValue = '';
1544 }
f0d58350 1545 $relPrefix = $field . $relationField;
1860fab0 1546
1547 if (is_object($relDAO) && $relationField == 'id') {
f0d58350 1548 $row[$relPrefix] = $relDAO->contact_id;
1860fab0 1549 }
1550 elseif (is_array($relationValue) && $relationField == 'location') {
1551 foreach ($relationValue as $ltype => $val) {
a16a432a 1552 // If the location name has a space in it the we need to handle that. This
1553 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1554 // improve it should be secure in the knowled it will be caught.
1555 $ltype = str_replace(' ', '_', $ltype);
1860fab0 1556 foreach (array_keys($val) as $fld) {
1557 $type = explode('-', $fld);
1558 $fldValue = "{$ltype}-" . $type[0];
1559 if (!empty($type[1])) {
1560 $fldValue .= "-" . $type[1];
1561 }
1562 // CRM-3157: localise country, region (both have ‘country’ context)
1563 // and state_province (‘province’ context)
1564 switch (TRUE) {
1565 case (!is_object($relDAO)):
1566 $row[$field . '_' . $fldValue] = '';
1567 break;
1568
1569 case in_array('country', $type):
1570 case in_array('world_region', $type):
1571 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1572 array('context' => 'country')
1573 );
1574 break;
1575
1576 case in_array('state_province', $type):
1577 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1578 array('context' => 'province')
1579 );
1580 break;
1581
1582 default:
1583 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1584 break;
1585 }
1586 }
1587 }
1588 }
1589 elseif (isset($fieldValue) && $fieldValue != '') {
1590 //check for custom data
1591 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
f0d58350 1592 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1860fab0 1593 }
1594 else {
1595 //normal relationship fields
1596 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1597 switch ($relationField) {
1598 case 'country':
1599 case 'world_region':
f0d58350 1600 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1860fab0 1601 break;
1602
1603 case 'state_province':
f0d58350 1604 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1860fab0 1605 break;
1606
1607 default:
f0d58350 1608 $row[$relPrefix] = $fieldValue;
1860fab0 1609 break;
1610 }
1611 }
1612 }
1613 else {
1614 // if relation field is empty or null
f0d58350 1615 $row[$relPrefix] = '';
1860fab0 1616 }
1617 }
1618 }
1619
814065a3 1620 /**
1621 * Get the ids that we want to get related contact details for.
1622 *
1623 * @param array $ids
1624 * @param int $exportMode
1625 *
1626 * @return array
1627 */
1628 protected static function getIDsForRelatedContact($ids, $exportMode) {
1629 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
1630 return $ids;
1631 }
1632 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1633 $relIDs = [];
1634 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1635 $dao = CRM_Core_DAO::executeQuery("
1636 SELECT contact_id FROM civicrm_activity_contact
1637 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1638 record_type_id = {$sourceID}
1639 ");
1640
1641 while ($dao->fetch()) {
1642 $relIDs[] = $dao->contact_id;
1643 }
1644 return $relIDs;
1645 }
1646 $component = self::exportComponent($exportMode);
1647
1648 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
1649 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
1650 }
1651 else {
1652 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
1653 }
1654 }
1655
44f8f95c 1656 /**
1657 * @param $selectAll
1658 * @param $ids
439355f5 1659 * @param \CRM_Export_BAO_ExportProcessor $processor
44f8f95c 1660 * @param $componentTable
44f8f95c 1661 */
ce12a9e0 1662 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
44f8f95c 1663 $allRelContactArray = $relationQuery = array();
439355f5 1664 $queryMode = $processor->getQueryMode();
1665 $exportMode = $processor->getExportMode();
44f8f95c 1666
ce12a9e0 1667 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1668 $allRelContactArray[$relationshipKey] = array();
1669 // build Query for each relationship
1670 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1671 NULL, FALSE, FALSE, $queryMode
1672 );
1673 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1674
1675 list($id, $direction) = explode('_', $relationshipKey, 2);
1676 // identify the relationship direction
1677 $contactA = 'contact_id_a';
1678 $contactB = 'contact_id_b';
1679 if ($direction == 'b_a') {
1680 $contactA = 'contact_id_b';
1681 $contactB = 'contact_id_a';
1682 }
1683 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
1684
1685 $relationshipJoin = $relationshipClause = '';
1686 if (!$selectAll && $componentTable) {
1687 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1688 }
1689 elseif (!empty($relIDs)) {
1690 $relID = implode(',', $relIDs);
1691 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1692 }
44f8f95c 1693
ce12a9e0 1694 $relationFrom = " {$relationFrom}
1695 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1696 {$relationshipJoin} ";
1697
1698 //check for active relationship status only
1699 $today = date('Ymd');
1700 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1701 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1702 $relationGroupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($relationQuery->_select, "crel.{$contactA}");
1703 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1704 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
1705
1706 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
1707 while ($allRelContactDAO->fetch()) {
1708 $relationQuery->convertToPseudoNames($allRelContactDAO);
1709 $row = [];
1710 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1711 self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1712 foreach (array_keys($relationReturnProperties) as $property) {
1713 if ($property === 'location') {
1714 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1715 // $processor->setRelationshipValue from fetchRelationshipDetails
1716 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1717 foreach (array_keys($locationValues) as $locationValue) {
1718 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1719 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
1720 }
1721 }
1722 }
1723 else {
1724 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
1725 }
44f8f95c 1726 }
44f8f95c 1727 }
1728 }
44f8f95c 1729 }
1730
3663269c 1731 /**
1732 * @param $field
1733 * @param $iterationDAO
1734 * @param $fieldValue
1735 * @param $i18n
1736 * @param $metadata
3663269c 1737 * @param $paymentDetails
c66a5741 1738 *
1739 * @param \CRM_Export_BAO_ExportProcessor $processor
1740 *
3663269c 1741 * @return string
1742 */
c66a5741 1743 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor) {
3663269c 1744
1745 if ($field == 'id') {
1746 return $iterationDAO->contact_id;
1747 // special case for calculated field
1748 }
1749 elseif ($field == 'source_contact_id') {
1750 return $iterationDAO->contact_id;
1751 }
1752 elseif ($field == 'pledge_balance_amount') {
1753 return $iterationDAO->pledge_amount - $iterationDAO->pledge_total_paid;
1754 // special case for calculated field
1755 }
1756 elseif ($field == 'pledge_next_pay_amount') {
1757 return $iterationDAO->pledge_next_pay_amount + $iterationDAO->pledge_outstanding_amount;
1758 }
1759 elseif (isset($fieldValue) &&
1760 $fieldValue != ''
1761 ) {
1762 //check for custom data
1763 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($field)) {
1764 return CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1765 }
1766
1767 elseif (in_array($field, array(
1768 'email_greeting',
1769 'postal_greeting',
1770 'addressee',
1771 ))) {
1772 //special case for greeting replacement
1773 $fldValue = "{$field}_display";
1774 return $iterationDAO->$fldValue;
1775 }
1776 else {
1777 //normal fields with a touch of CRM-3157
1778 switch ($field) {
1779 case 'country':
1780 case 'world_region':
1781 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
1782
1783 case 'state_province':
1784 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
1785
1786 case 'gender':
1787 case 'preferred_communication_method':
1788 case 'preferred_mail_format':
1789 case 'communication_style':
1790 return $i18n->crm_translate($fieldValue);
1791
1792 default:
1793 if (isset($metadata[$field])) {
1794 // No I don't know why we do it this way & whether we could
1795 // make better use of pseudoConstants.
1796 if (!empty($metadata[$field]['context'])) {
1797 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1798 }
1799 if (!empty($metadata[$field]['pseudoconstant'])) {
1800 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1801 // call an external function until sure it is not increasing php processing given this
1802 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1803 // That can be next refactor...
1804 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1805 // but I have to reach a stable point....
1806 $varName = $metadata[$field]['pseudoconstant']['var'];
1807 if ($varName === 'imProviders') {
1808 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1809 }
1810 if ($varName === 'phoneTypes') {
1811 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
1812 }
1813 }
1814
1815 }
1816 return $fieldValue;
1817 }
1818 }
1819 }
c66a5741 1820 elseif ($processor->isExportSpecifiedPaymentFields() && array_key_exists($field, self::componentPaymentFields())) {
1821 $paymentTableId = $processor->getPaymentTableID();
3663269c 1822 $paymentData = CRM_Utils_Array::value($iterationDAO->$paymentTableId, $paymentDetails);
1823 $payFieldMapper = array(
1824 'componentPaymentField_total_amount' => 'total_amount',
1825 'componentPaymentField_contribution_status' => 'contribution_status',
1826 'componentPaymentField_payment_instrument' => 'pay_instru',
1827 'componentPaymentField_transaction_id' => 'trxn_id',
1828 'componentPaymentField_received_date' => 'receive_date',
1829 );
1830 return CRM_Utils_Array::value($payFieldMapper[$field], $paymentData, '');
1831 }
1832 else {
1833 // if field is empty or null
1834 return '';
1835 }
1836 }
1837
6a488035 1838}