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