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