Move greeting params retrieval to the place in the code where it is used
[civicrm-core.git] / CRM / Export / BAO / Export.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
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
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
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
f34f5143
SL
44 /**
45 * Get Export component
46 *
47 * @param int $exportMode
48 * Export mode.
49 *
7b966967 50 * @return string
748450ad 51 * CiviCRM Export Component
f34f5143 52 */
7bf9f91e 53 public static function exportComponent($exportMode) {
f34f5143
SL
54 switch ($exportMode) {
55 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
56 $component = 'civicrm_contribution';
57 break;
58
59 case CRM_Export_Form_Select::EVENT_EXPORT:
60 $component = 'civicrm_participant';
61 break;
62
63 case CRM_Export_Form_Select::MEMBER_EXPORT:
64 $component = 'civicrm_membership';
65 break;
66
67 case CRM_Export_Form_Select::PLEDGE_EXPORT:
68 $component = 'civicrm_pledge';
69 break;
70
71 case CRM_Export_Form_Select::GRANT_EXPORT:
72 $component = 'civicrm_grant';
73 break;
74 }
75 return $component;
76 }
77
748450ad 78 /**
f1ff3965 79 * Get Query Group By Clause
439355f5 80 * @param \CRM_Export_BAO_ExportProcessor $processor
748450ad 81 * Export Mode
748450ad
SL
82 * @param array $returnProperties
83 * Return Properties
0cc9927d
SL
84 * @param object $query
85 * CRM_Contact_BAO_Query
86 *
7b966967 87 * @return string
748450ad
SL
88 * Group By Clause
89 */
439355f5 90 public static function getGroupBy($processor, $returnProperties, $query) {
d5148d71 91 $groupBy = NULL;
439355f5 92 $exportMode = $processor->getExportMode();
93 $queryMode = $processor->getQueryMode();
748450ad
SL
94 if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
95 CRM_Utils_Array::value('notes', $returnProperties) ||
96 // CRM-9552
97 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
98 ) {
3636b520 99 $groupBy = "contact_a.id";
748450ad
SL
100 }
101
102 switch ($exportMode) {
103 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
3636b520 104 $groupBy = 'civicrm_contribution.id';
748450ad
SL
105 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
106 // especial group by when soft credit columns are included
d5148d71 107 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
748450ad
SL
108 }
109 break;
110
111 case CRM_Export_Form_Select::EVENT_EXPORT:
3636b520 112 $groupBy = 'civicrm_participant.id';
748450ad
SL
113 break;
114
115 case CRM_Export_Form_Select::MEMBER_EXPORT:
3636b520 116 $groupBy = "civicrm_membership.id";
748450ad
SL
117 break;
118 }
119
120 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
3636b520 121 $groupBy = "civicrm_activity.id ";
748450ad 122 }
ee027e3b 123
d5148d71 124 return $groupBy ? ' GROUP BY ' . implode(', ', (array) $groupBy) : '';
748450ad
SL
125 }
126
6a488035 127 /**
fe482240 128 * Get the list the export fields.
6a488035 129 *
b9add4b3
TO
130 * @param int $selectAll
131 * User preference while export.
132 * @param array $ids
133 * Contact ids.
134 * @param array $params
135 * Associated array of fields.
136 * @param string $order
137 * Order by clause.
138 * @param array $fields
139 * Associated array of fields.
140 * @param array $moreReturnProperties
141 * Additional return fields.
142 * @param int $exportMode
143 * Export mode.
144 * @param string $componentClause
145 * Component clause.
146 * @param string $componentTable
147 * Component table.
148 * @param bool $mergeSameAddress
149 * Merge records if they have same address.
150 * @param bool $mergeSameHousehold
151 * Merge records if they belong to the same household.
6c8f6e67
EM
152 *
153 * @param array $exportParams
154 * @param string $queryOperator
6a488035 155 *
c7224305 156 * @return array|null
157 * An array can be requested from within a unit test.
158 *
159 * @throws \CRM_Core_Exception
6a488035 160 */
317fceb4 161 public static function exportComponents(
97f6897c 162 $selectAll,
6a488035
TO
163 $ids,
164 $params,
165 $order = NULL,
166 $fields = NULL,
167 $moreReturnProperties = NULL,
168 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
169 $componentClause = NULL,
170 $componentTable = NULL,
171 $mergeSameAddress = FALSE,
172 $mergeSameHousehold = FALSE,
be2fb01f 173 $exportParams = [],
6a488035
TO
174 $queryOperator = 'AND'
175 ) {
ef51caa8 176
6d52bfe5 177 $isPostalOnly = (
178 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
179 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
180 );
181
182 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly);
806c5e1e 183 $returnProperties = $processor->getReturnProperties();
c66a5741 184 $paymentTableId = $processor->getPaymentTableID();
6a488035
TO
185
186 if ($mergeSameAddress) {
187 //make sure the addressee fields are selected
188 //while using merge same address feature
189 $returnProperties['addressee'] = 1;
190 $returnProperties['postal_greeting'] = 1;
191 $returnProperties['email_greeting'] = 1;
192 $returnProperties['street_name'] = 1;
193 $returnProperties['household_name'] = 1;
194 $returnProperties['street_address'] = 1;
195 $returnProperties['city'] = 1;
196 $returnProperties['state_province'] = 1;
197
198 // some columns are required for assistance incase they are not already present
be2fb01f
CW
199 $exportParams['merge_same_address']['temp_columns'] = [];
200 $tempColumns = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
6a488035
TO
201 foreach ($tempColumns as $column) {
202 if (!array_key_exists($column, $returnProperties)) {
203 $returnProperties[$column] = 1;
204 $column = $column == 'id' ? 'civicrm_primary_id' : $column;
205 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
206 }
207 }
208 }
209
8cc574cf 210 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
6a488035
TO
211 // If an Additional Group is selected, then all contacts in that group are
212 // added to the export set (filtering out duplicates).
213 $query = "
214INSERT 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";
215 CRM_Core_DAO::executeQuery($query);
216 }
217
218 if ($moreReturnProperties) {
219 // fix for CRM-7066
a7488080 220 if (!empty($moreReturnProperties['group'])) {
6a488035
TO
221 unset($moreReturnProperties['group']);
222 $moreReturnProperties['groups'] = 1;
223 }
224 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
225 }
226
12a6fdef 227 if ($processor->getRequestedFields() &&
228 $processor->isPostalableOnly()
6a488035 229 ) {
be2fb01f 230 $postalColumns = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
12a6fdef 231 $exportParams['postal_mailing_export']['temp_columns'] = [];
6a488035
TO
232 foreach ($postalColumns as $column) {
233 if (!array_key_exists($column, $returnProperties)) {
234 $returnProperties[$column] = 1;
235 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
236 }
237 }
238 }
239
9e49a7b8
PJ
240 // rectify params to what proximity search expects if there is a value for prox_distance
241 // CRM-7021
242 if (!empty($params)) {
243 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
244 }
245
71464b73 246 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
6a488035
TO
247
248 if ($mergeSameHousehold == 1) {
0dc29086 249 if (empty($returnProperties['id'])) {
6a488035
TO
250 $returnProperties['id'] = 1;
251 }
252
136f69a8 253 $processor->setHouseholdMergeReturnProperties(array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1)));
6a488035
TO
254 }
255
ebebd629 256 // This perhaps only needs calling when $mergeSameHousehold == 1
ce12a9e0 257 self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
6a488035
TO
258
259 // make sure the groups stuff is included only if specifically specified
260 // by the fields param (CRM-1969), else we limit the contacts outputted to only
261 // ones that are part of a group
a7488080 262 if (!empty($returnProperties['groups'])) {
6a488035
TO
263 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
264 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
265 // total hack for export, CRM-3618
266 $from = str_replace($oldClause,
267 $newClause,
268 $from
269 );
270 }
271
72c506e9 272 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
34b773b7 273 if (!$selectAll && $componentTable) {
6a488035
TO
274 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
275 }
276 elseif ($componentClause) {
72c506e9 277 $whereClauses[] = $componentClause;
6a488035
TO
278 }
279
14a08308 280 // CRM-13982 - check if is deleted
14a08308 281 foreach ($params as $value) {
282 if ($value[0] == 'contact_is_deleted') {
72c506e9 283 unset($whereClauses['trash_clause']);
14a08308 284 }
285 }
17bc4f1b 286
0b02cdf2 287 if (empty($where)) {
72c506e9 288 $where = "WHERE " . implode(' AND ', $whereClauses);
14a08308 289 }
17bc4f1b 290 else {
72c506e9 291 $where .= " AND " . implode(' AND ', $whereClauses);
14a08308 292 }
293
6a488035
TO
294 $queryString = "$select $from $where $having";
295
439355f5 296 $groupBy = self::getGroupBy($processor, $returnProperties, $query);
8a13a745 297
6a488035 298 $queryString .= $groupBy;
33a5a53d 299
6a488035 300 if ($order) {
7f5cc737 301 // always add contact_a.id to the ORDER clause
302 // so the order is deterministic
303 //CRM-15301
304 if (strpos('contact_a.id', $order) === FALSE) {
305 $order .= ", contact_a.id";
306 }
5a6afd32 307
6a488035
TO
308 list($field, $dir) = explode(' ', $order, 2);
309 $field = trim($field);
a7488080 310 if (!empty($returnProperties[$field])) {
33a5a53d 311 //CRM-15301
312 $queryString .= " ORDER BY $order";
6a488035
TO
313 }
314 }
315
6a488035
TO
316 $addPaymentHeader = FALSE;
317
943e6943 318 list($outputColumns, $metadata) = self::getExportStructureArrays($returnProperties, $processor);
319
c8925481 320 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
321 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
322 // test exists covering this...
323 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
324 $processor->setColumnAsCalculationOnly($field);
325 }
326 }
327
943e6943 328 $paymentDetails = [];
c66a5741 329 if ($processor->isExportPaymentFields()) {
6a488035
TO
330 // get payment related in for event and members
331 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
d77aba4b 332 //get all payment headers.
7460c131
AS
333 // If we haven't selected specific payment fields, load in all the
334 // payment headers.
c66a5741 335 if (!$processor->isExportSpecifiedPaymentFields()) {
d77aba4b
AS
336 if (!empty($paymentDetails)) {
337 $addPaymentHeader = TRUE;
943e6943 338 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
339 $processor->addOutputSpecification($paymentField);
340 }
d77aba4b 341 }
6a488035 342 }
6a488035
TO
343 }
344
be2fb01f 345 $componentDetails = [];
6a488035
TO
346
347 $rowCount = self::EXPORT_ROW_COUNT;
348 $offset = 0;
349 // we write to temp table often to avoid using too much memory
350 $tempRowCount = 100;
351
352 $count = -1;
353
28254dcb 354 $headerRows = $processor->getHeaderRows();
2cd3d767 355 $sqlColumns = $processor->getSQLColumns();
68989e71 356 $processor->setTemporaryTable(self::createTempTable($sqlColumns));
24c7dffa 357 $limitReached = FALSE;
0b94b406 358
24c7dffa 359 while (!$limitReached) {
6a488035 360 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
6f5824c1 361 CRM_Core_DAO::disableFullGroupByMode();
bab4f15e 362 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
6f5824c1 363 CRM_Core_DAO::reenableFullGroupByMode();
24c7dffa 364 // If this is less than our limit by the end of the iteration we do not need to run the query again to
365 // check if some remain.
366 $rowsThisIteration = 0;
6a488035 367
bab4f15e 368 while ($iterationDAO->fetch()) {
6a488035 369 $count++;
24c7dffa 370 $rowsThisIteration++;
6e2de55d 371 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
136f69a8 372 if ($row === FALSE) {
373 continue;
374 }
6a488035
TO
375
376 // add component info
377 // write the row to a file
378 $componentDetails[] = $row;
379
380 // output every $tempRowCount rows
381 if ($count % $tempRowCount == 0) {
68989e71 382 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
be2fb01f 383 $componentDetails = [];
6a488035
TO
384 }
385 }
24c7dffa 386 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
387 $limitReached = TRUE;
388 }
6a488035
TO
389 $offset += $rowCount;
390 }
391
68989e71 392 if ($processor->getTemporaryTable()) {
393 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
6a488035
TO
394
395 // do merge same address and merge same household processing
396 if ($mergeSameAddress) {
68989e71 397 self::mergeSameAddress($processor, $sqlColumns, $exportParams);
6a488035
TO
398 }
399
6a488035 400 // call export hook
68989e71 401 $table = $processor->getTemporaryTable();
402 CRM_Utils_Hook::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
403 if ($table !== $processor->getTemporaryTable()) {
404 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
405 $processor->setTemporaryTable($table);
406 }
6a488035 407
ef51caa8 408 // In order to be able to write a unit test against this function we need to suppress
409 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
410 if (empty($exportParams['suppress_csv_for_testing'])) {
68989e71 411 self::writeCSVFromTable($headerRows, $sqlColumns, $processor);
ef51caa8 412 }
994a070c 413 else {
b7db6051 414 // return tableName sqlColumns headerRows in test context
68989e71 415 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
994a070c 416 }
6a488035
TO
417
418 // delete the export temp table and component table
68989e71 419 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
6a488035 420 CRM_Core_DAO::executeQuery($sql);
2f68ef20 421 CRM_Core_DAO::reenableFullGroupByMode();
68989e71 422 CRM_Utils_System::civiExit(0, ['processor' => $processor]);
6a488035
TO
423 }
424 else {
2f68ef20 425 CRM_Core_DAO::reenableFullGroupByMode();
c7224305 426 throw new CRM_Core_Exception(ts('No records to export'));
6a488035
TO
427 }
428 }
429
6a488035 430 /**
100fef9d 431 * Handle import error file creation.
6a488035 432 */
00be9182 433 public static function invoke() {
a3d827a7
CW
434 $type = CRM_Utils_Request::retrieve('type', 'Positive');
435 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
6a488035
TO
436 if (empty($parserName) || empty($type)) {
437 return;
438 }
439
440 // clean and ensure parserName is a valid string
441 $parserName = CRM_Utils_String::munge($parserName);
442 $parserClass = explode('_', $parserName);
443
444 // make sure parserClass is in the CRM namespace and
445 // at least 3 levels deep
446 if ($parserClass[0] == 'CRM' &&
447 count($parserClass) >= 3
448 ) {
d3e86119 449 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
6a488035
TO
450 // ensure the functions exists
451 if (method_exists($parserName, 'errorFileName') &&
452 method_exists($parserName, 'saveFileName')
453 ) {
454 $errorFileName = $parserName::errorFileName($type);
455 $saveFileName = $parserName::saveFileName($type);
456 if (!empty($errorFileName) && !empty($saveFileName)) {
d42a224c
CW
457 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
458 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
459 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
460 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
461 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
6a488035
TO
462
463 readfile($errorFileName);
464 }
465 }
466 }
467 CRM_Utils_System::civiExit();
468 }
469
e0ef6999
EM
470 /**
471 * @param $customSearchClass
472 * @param $formValues
473 * @param $order
474 */
00be9182 475 public static function exportCustom($customSearchClass, $formValues, $order) {
6a488035
TO
476 $ext = CRM_Extension_System::singleton()->getMapper();
477 if (!$ext->isExtensionClass($customSearchClass)) {
d3e86119 478 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
6a488035
TO
479 }
480 else {
d3e86119 481 require_once $ext->classToPath($customSearchClass);
6a488035
TO
482 }
483 $search = new $customSearchClass($formValues);
484
485 $includeContactIDs = FALSE;
486 if ($formValues['radio_ts'] == 'ts_sel') {
487 $includeContactIDs = TRUE;
488 }
489
490 $sql = $search->all(0, 0, $order, $includeContactIDs);
491
492 $columns = $search->columns();
493
494 $header = array_keys($columns);
495 $fields = array_values($columns);
496
be2fb01f 497 $rows = [];
97f6897c 498 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
499 $alterRow = FALSE;
500 if (method_exists($search, 'alterRow')) {
501 $alterRow = TRUE;
502 }
503 while ($dao->fetch()) {
be2fb01f 504 $row = [];
6a488035
TO
505
506 foreach ($fields as $field) {
37990ecd
JV
507 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
508 $row[$field] = $dao->$unqualified_field;
6a488035
TO
509 }
510 if ($alterRow) {
511 $search->alterRow($row);
512 }
513 $rows[] = $row;
514 }
515
620eae15 516 CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
6a488035
TO
517 CRM_Utils_System::civiExit();
518 }
519
e0ef6999 520 /**
68989e71 521 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999
EM
522 * @param $details
523 * @param $sqlColumns
524 */
68989e71 525 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
526 $tableName = $processor->getTemporaryTable();
6a488035
TO
527 if (empty($details)) {
528 return;
529 }
530
531 $sql = "
532SELECT max(id)
533FROM $tableName
534";
535
536 $id = CRM_Core_DAO::singleValueQuery($sql);
537 if (!$id) {
538 $id = 0;
539 }
540
be2fb01f 541 $sqlClause = [];
6a488035 542
610f72e1 543 foreach ($details as $row) {
6a488035 544 $id++;
be2fb01f 545 $valueString = [$id];
610f72e1 546 foreach ($row as $value) {
6a488035
TO
547 if (empty($value)) {
548 $valueString[] = "''";
549 }
550 else {
551 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
552 }
553 }
554 $sqlClause[] = '(' . implode(',', $valueString) . ')';
555 }
dfab581c
PN
556 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
557 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
6a488035
TO
558
559 $sqlValueString = implode(",\n", $sqlClause);
560
561 $sql = "
562INSERT INTO $tableName $sqlColumnString
563VALUES $sqlValueString
564";
6a488035
TO
565 CRM_Core_DAO::executeQuery($sql);
566 }
567
e0ef6999
EM
568 /**
569 * @param $sqlColumns
570 *
571 * @return string
572 */
610f72e1 573 public static function createTempTable($sqlColumns) {
6a488035 574 //creating a temporary table for the search result that need be exported
0033aaaf 575 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
6a488035
TO
576
577 // also create the sql table
4089dea0 578 $exportTempTable->drop();
6a488035 579
dfab581c
PN
580 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
581 if (!empty($sqlColumns)) {
582 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
583 }
584
585 $sql .= "\n PRIMARY KEY ( id )";
6a488035 586
6a488035 587 // add indexes for street_address and household_name if present
be2fb01f 588 $addIndices = [
6a488035
TO
589 'street_address',
590 'household_name',
591 'civicrm_primary_id',
be2fb01f 592 ];
6a488035
TO
593
594 foreach ($addIndices as $index) {
595 if (isset($sqlColumns[$index])) {
596 $sql .= ",
597 INDEX index_{$index}( $index )
598";
599 }
600 }
601
4089dea0 602 $exportTempTable->createWithColumns($sql);
603 return $exportTempTable->getName();
6a488035
TO
604 }
605
e0ef6999 606 /**
68989e71 607 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999 608 * @param $sqlColumns
100fef9d 609 * @param array $exportParams
e0ef6999 610 */
68989e71 611 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
5790f42f 612 $greetingOptions = CRM_Export_Form_Select::getGreetingOptions();
613
614 if (!empty($greetingOptions)) {
615 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
616 foreach ($greetingOptions as $key => $value) {
617 if ($option = CRM_Utils_Array::value($key, $exportParams)) {
618 if ($greetingOptions[$key][$option] == ts('Other')) {
619 $exportParams[$key] = $exportParams["{$key}_other"];
620 }
621 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
622 $exportParams[$key] = '';
623 }
624 else {
625 $exportParams[$key] = $greetingOptions[$key][$option];
626 }
627 }
628 }
629 }
68989e71 630 $tableName = $processor->getTemporaryTable();
6a488035
TO
631 // check if any records are present based on if they have used shared address feature,
632 // and not based on if city / state .. matches.
633 $sql = "
634SELECT r1.id as copy_id,
635 r1.civicrm_primary_id as copy_contact_id,
636 r1.addressee as copy_addressee,
637 r1.addressee_id as copy_addressee_id,
638 r1.postal_greeting as copy_postal_greeting,
639 r1.postal_greeting_id as copy_postal_greeting_id,
640 r2.id as master_id,
641 r2.civicrm_primary_id as master_contact_id,
642 r2.postal_greeting as master_postal_greeting,
643 r2.postal_greeting_id as master_postal_greeting_id,
644 r2.addressee as master_addressee,
645 r2.addressee_id as master_addressee_id
646FROM $tableName r1
647INNER JOIN civicrm_address adr ON r1.master_id = adr.id
648INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
649ORDER BY r1.id";
650 $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE);
651
652 // find all the records that have the same street address BUT not in a household
653 // require match on city and state as well
654 $sql = "
655SELECT r1.id as master_id,
656 r1.civicrm_primary_id as master_contact_id,
657 r1.postal_greeting as master_postal_greeting,
658 r1.postal_greeting_id as master_postal_greeting_id,
659 r1.addressee as master_addressee,
660 r1.addressee_id as master_addressee_id,
661 r2.id as copy_id,
662 r2.civicrm_primary_id as copy_contact_id,
663 r2.postal_greeting as copy_postal_greeting,
664 r2.postal_greeting_id as copy_postal_greeting_id,
665 r2.addressee as copy_addressee,
666 r2.addressee_id as copy_addressee_id
667FROM $tableName r1
668LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
669 r1.city = r2.city AND
670 r1.state_province_id = r2.state_province_id )
671WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
672AND ( r2.household_name IS NULL OR r2.household_name = '' )
673AND ( r1.street_address != '' )
674AND r2.id > r1.id
675ORDER BY r1.id
676";
677 $merge = self::_buildMasterCopyArray($sql, $exportParams);
678
679 // unset ids from $merge already present in $linkedMerge
680 foreach ($linkedMerge as $masterID => $values) {
be2fb01f 681 $keys = [$masterID];
6a488035
TO
682 $keys = array_merge($keys, array_keys($values['copy']));
683 foreach ($merge as $mid => $vals) {
684 if (in_array($mid, $keys)) {
685 unset($merge[$mid]);
686 }
687 else {
688 foreach ($values['copy'] as $copyId) {
689 if (in_array($copyId, $keys)) {
690 unset($merge[$mid]['copy'][$copyId]);
691 }
692 }
693 }
694 }
695 }
696 $merge = $merge + $linkedMerge;
697
698 foreach ($merge as $masterID => $values) {
699 $sql = "
700UPDATE $tableName
701SET addressee = %1, postal_greeting = %2, email_greeting = %3
702WHERE id = %4
703";
be2fb01f
CW
704 $params = [
705 1 => [$values['addressee'], 'String'],
706 2 => [$values['postalGreeting'], 'String'],
707 3 => [$values['emailGreeting'], 'String'],
708 4 => [$masterID, 'Integer'],
709 ];
6a488035
TO
710 CRM_Core_DAO::executeQuery($sql, $params);
711
712 // delete all copies
97f6897c 713 $deleteIDs = array_keys($values['copy']);
6a488035 714 $deleteIDString = implode(',', $deleteIDs);
97f6897c 715 $sql = "
6a488035
TO
716DELETE FROM $tableName
717WHERE id IN ( $deleteIDString )
718";
719 CRM_Core_DAO::executeQuery($sql);
720 }
721
722 // unset temporary columns that were added for postal mailing format
c8925481 723 // @todo - this part is pretty close to ready to be removed....
6a488035
TO
724 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
725 $unsetKeys = array_keys($sqlColumns);
726 foreach ($unsetKeys as $headerKey => $sqlColKey) {
727 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
de6ff509 728 unset($sqlColumns[$sqlColKey]);
6a488035
TO
729 }
730 }
731 }
732 }
733
e0ef6999 734 /**
100fef9d
CW
735 * @param int $contactId
736 * @param array $exportParams
e0ef6999
EM
737 *
738 * @return array
739 */
00be9182 740 public static function _replaceMergeTokens($contactId, $exportParams) {
be2fb01f 741 $greetings = [];
6a488035
TO
742 $contact = NULL;
743
be2fb01f 744 $greetingFields = [
6a488035
TO
745 'postal_greeting',
746 'addressee',
be2fb01f 747 ];
6a488035 748 foreach ($greetingFields as $greeting) {
a7488080 749 if (!empty($exportParams[$greeting])) {
6a488035
TO
750 $greetingLabel = $exportParams[$greeting];
751 if (empty($contact)) {
be2fb01f 752 $values = [
6a488035
TO
753 'id' => $contactId,
754 'version' => 3,
be2fb01f 755 ];
6a488035
TO
756 $contact = civicrm_api('contact', 'get', $values);
757
a7488080 758 if (!empty($contact['is_error'])) {
6a488035
TO
759 return $greetings;
760 }
761 $contact = $contact['values'][$contact['id']];
762 }
763
be2fb01f 764 $tokens = ['contact' => $greetingLabel];
6a488035
TO
765 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
766 }
767 }
768 return $greetings;
769 }
770
771 /**
772 * The function unsets static part of the string, if token is the dynamic part.
54957108 773 *
6a488035
TO
774 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
775 * i.e 'Hello Alan' => converted to => 'Alan'
54957108 776 *
777 * @param string $parsedString
778 * @param string $defaultGreeting
779 * @param bool $addressMergeGreetings
780 * @param string $greetingType
781 *
782 * @return mixed
6a488035 783 */
317fceb4 784 public static function _trimNonTokens(
97f6897c 785 &$parsedString, $defaultGreeting,
353ffa53 786 $addressMergeGreetings, $greetingType = 'postal_greeting'
6a488035 787 ) {
a7488080 788 if (!empty($addressMergeGreetings[$greetingType])) {
6a488035
TO
789 $greetingLabel = $addressMergeGreetings[$greetingType];
790 }
791 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
792
793 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
794 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
795 foreach ($stringsToBeReplaced as $key => $string) {
796 // to keep one space
797 $stringsToBeReplaced[$key] = ltrim($string);
798 }
799 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
800
801 return $parsedString;
802 }
803
e0ef6999
EM
804 /**
805 * @param $sql
100fef9d 806 * @param array $exportParams
e0ef6999
EM
807 * @param bool $sharedAddress
808 *
809 * @return array
810 */
00be9182 811 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
be2fb01f 812 static $contactGreetingTokens = [];
6a488035
TO
813
814 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
815 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
816
be2fb01f 817 $merge = $parents = [];
6a488035
TO
818 $dao = CRM_Core_DAO::executeQuery($sql);
819
820 while ($dao->fetch()) {
821 $masterID = $dao->master_id;
822 $copyID = $dao->copy_id;
823 $masterPostalGreeting = $dao->master_postal_greeting;
824 $masterAddressee = $dao->master_addressee;
825 $copyAddressee = $dao->copy_addressee;
826
827 if (!$sharedAddress) {
828 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
829 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
830 }
831 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
832 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
833 );
834 $masterAddressee = CRM_Utils_Array::value('addressee',
835 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
836 );
837
838 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
839 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
840 }
841 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
842 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
843 );
844 $copyAddressee = CRM_Utils_Array::value('addressee',
845 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
846 );
847 }
848
849 if (!isset($merge[$masterID])) {
850 // check if this is an intermediate child
851 // this happens if there are 3 or more matches a,b, c
852 // the above query will return a, b / a, c / b, c
853 // we might be doing a bit more work, but for now its ok, unless someone
854 // knows how to fix the query above
855 if (isset($parents[$masterID])) {
856 $masterID = $parents[$masterID];
857 }
858 else {
be2fb01f 859 $merge[$masterID] = [
6a488035 860 'addressee' => $masterAddressee,
be2fb01f 861 'copy' => [],
6a488035 862 'postalGreeting' => $masterPostalGreeting,
be2fb01f 863 ];
6a488035
TO
864 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
865 }
866 }
867 $parents[$copyID] = $masterID;
868
869 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
870
a7488080 871 if (!empty($exportParams['postal_greeting_other']) &&
6a488035
TO
872 count($merge[$masterID]['copy']) >= 1
873 ) {
874 // use static greetings specified if no of contacts > 2
875 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
876 }
877 elseif ($copyPostalGreeting) {
878 self::_trimNonTokens($copyPostalGreeting,
879 $postalOptions[$dao->copy_postal_greeting_id],
880 $exportParams
881 );
882 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
883 // if there happens to be a duplicate, remove it
884 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
885 }
886
a7488080 887 if (!empty($exportParams['addressee_other']) &&
6a488035
TO
888 count($merge[$masterID]['copy']) >= 1
889 ) {
890 // use static greetings specified if no of contacts > 2
891 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
892 }
893 elseif ($copyAddressee) {
894 self::_trimNonTokens($copyAddressee,
895 $addresseeOptions[$dao->copy_addressee_id],
896 $exportParams, 'addressee'
897 );
898 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
899 }
900 }
901 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
902 }
903
904 return $merge;
905 }
906
e0ef6999 907 /**
e0ef6999
EM
908 * @param $headerRows
909 * @param $sqlColumns
70107611 910 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999 911 */
68989e71 912 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
913 $exportTempTable = $processor->getTemporaryTable();
70107611 914 $exportMode = $processor->getExportMode();
6a488035 915 $writeHeader = TRUE;
97f6897c
TO
916 $offset = 0;
917 $limit = self::EXPORT_ROW_COUNT;
6a488035
TO
918
919 $query = "SELECT * FROM $exportTempTable";
920
921 while (1) {
922 $limitQuery = $query . "
923LIMIT $offset, $limit
924";
925 $dao = CRM_Core_DAO::executeQuery($limitQuery);
926
927 if ($dao->N <= 0) {
928 break;
929 }
930
be2fb01f 931 $componentDetails = [];
6a488035 932 while ($dao->fetch()) {
be2fb01f 933 $row = [];
6a488035
TO
934
935 foreach ($sqlColumns as $column => $dontCare) {
936 $row[$column] = $dao->$column;
937 }
938 $componentDetails[] = $row;
939 }
29034a98 940 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
6a488035
TO
941 $headerRows,
942 $componentDetails,
97f6897c 943 NULL,
70107611 944 $writeHeader
945 );
6a488035 946
97f6897c 947 $writeHeader = FALSE;
6a488035
TO
948 $offset += $limit;
949 }
950 }
951
d77aba4b
AS
952 /**
953 * Build componentPayment fields.
0e32ed68 954 *
955 * This is no longer used by export but BAO_Mapping still calls it & we
956 * should find a generic way to handle this or move this to that class.
957 *
958 * @deprecated
d77aba4b 959 */
00be9182 960 public static function componentPaymentFields() {
d77aba4b 961 static $componentPaymentFields;
97f6897c 962 if (!isset($componentPaymentFields)) {
be2fb01f 963 $componentPaymentFields = [
97f6897c 964 'componentPaymentField_total_amount' => ts('Total Amount'),
d77aba4b 965 'componentPaymentField_contribution_status' => ts('Contribution Status'),
7bc6b5bb 966 'componentPaymentField_received_date' => ts('Date Received'),
536f0e02 967 'componentPaymentField_payment_instrument' => ts('Payment Method'),
97f6897c 968 'componentPaymentField_transaction_id' => ts('Transaction ID'),
be2fb01f 969 ];
d77aba4b
AS
970 }
971 return $componentPaymentFields;
972 }
96025800 973
12a36993 974 /**
975 * Get the various arrays that we use to structure our output.
976 *
977 * The extraction of these has been moved to a separate function for clarity and so that
978 * tests can be added - in particular on the $outputHeaders array.
979 *
980 * However it still feels a bit like something that I'm too polite to write down and this should be seen
981 * as a step on the refactoring path rather than how it should be.
982 *
983 * @param array $returnProperties
adabfa40 984 * @param \CRM_Export_BAO_ExportProcessor $processor
c66a5741 985 *
12a36993 986 * @return array
987 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
988 * alias for the field generated by BAO_Query object.
989 * - headerRows Array of the column header strings to put in the csv header - non-associative.
990 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
991 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
992 * I'm too embarassed to discuss here.
993 * The keys need
994 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
995 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
996 * in the main DAO loop is done once per row & that coule be 100,000 times.)
997 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
998 * - a) the function used is more efficient or
999 * - b) this code is old & outdated. Submit your answers to circular bin or better
1000 * yet find a way to comment them for posterity.
1001 */
2a48e887 1002 public static function getExportStructureArrays($returnProperties, $processor) {
be2fb01f 1003 $outputColumns = $metadata = [];
adabfa40 1004 $queryFields = $processor->getQueryFields();
12a36993 1005 foreach ($returnProperties as $key => $value) {
3883f8fb 1006 if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
1007 $outputColumns[$key] = $value;
ae5d4caf 1008 $processor->addOutputSpecification($key);
3883f8fb 1009 }
1010 elseif ($processor->isRelationshipTypeKey($key)) {
12a36993 1011 $outputColumns[$key] = $value;
3883f8fb 1012 foreach ($value as $relationField => $relationValue) {
1013 // below block is same as primary block (duplicate)
1014 if (isset($queryFields[$relationField]['title'])) {
5ebd7d09 1015 $processor->addOutputSpecification($relationField, $key);
3883f8fb 1016 }
1017 elseif (is_array($relationValue) && $relationField == 'location') {
1018 // fix header for location type case
1019 foreach ($relationValue as $ltype => $val) {
1020 foreach (array_keys($val) as $fld) {
1021 $type = explode('-', $fld);
5ebd7d09 1022 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
3883f8fb 1023 }
1024 }
1025 }
1026 }
12a36993 1027 }
1028 else {
1029 foreach ($value as $locationType => $locationFields) {
1030 foreach (array_keys($locationFields) as $locationFieldName) {
1031 $type = explode('-', $locationFieldName);
1032
1033 $actualDBFieldName = $type[0];
12a36993 1034 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
1035
1036 if (!empty($type[1])) {
1037 $daoFieldName .= "-" . $type[1];
12a36993 1038 }
5ebd7d09 1039 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
1040 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
12a36993 1041 $outputColumns[$daoFieldName] = TRUE;
1042 }
1043 }
1044 }
1045 }
be2fb01f 1046 return [$outputColumns, $metadata];
12a36993 1047 }
1048
1860fab0 1049 /**
1050 * Get the values of linked household contact.
1051 *
1052 * @param CRM_Core_DAO $relDAO
1053 * @param array $value
1054 * @param string $field
1055 * @param array $row
1056 */
1057 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1058 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
1059 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1060 $i18n = CRM_Core_I18n::singleton();
ce12a9e0 1061 $field = $field . '_';
1062
1860fab0 1063 foreach ($value as $relationField => $relationValue) {
1064 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1065 $fieldValue = $relDAO->$relationField;
1066 if ($relationField == 'phone_type_id') {
1067 $fieldValue = $phoneTypes[$relationValue];
1068 }
1069 elseif ($relationField == 'provider_id') {
1070 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
1071 }
1072 // CRM-13995
be2fb01f 1073 elseif (is_object($relDAO) && in_array($relationField, [
7b966967
SL
1074 'email_greeting',
1075 'postal_greeting',
1076 'addressee',
1077 ])) {
1860fab0 1078 //special case for greeting replacement
1079 $fldValue = "{$relationField}_display";
1080 $fieldValue = $relDAO->$fldValue;
1081 }
1082 }
1083 elseif (is_object($relDAO) && $relationField == 'state_province') {
1084 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
1085 }
1086 elseif (is_object($relDAO) && $relationField == 'country') {
1087 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
1088 }
1089 else {
1090 $fieldValue = '';
1091 }
f0d58350 1092 $relPrefix = $field . $relationField;
1860fab0 1093
1094 if (is_object($relDAO) && $relationField == 'id') {
f0d58350 1095 $row[$relPrefix] = $relDAO->contact_id;
1860fab0 1096 }
1097 elseif (is_array($relationValue) && $relationField == 'location') {
1098 foreach ($relationValue as $ltype => $val) {
a16a432a 1099 // If the location name has a space in it the we need to handle that. This
1100 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1101 // improve it should be secure in the knowled it will be caught.
1102 $ltype = str_replace(' ', '_', $ltype);
1860fab0 1103 foreach (array_keys($val) as $fld) {
1104 $type = explode('-', $fld);
1105 $fldValue = "{$ltype}-" . $type[0];
1106 if (!empty($type[1])) {
1107 $fldValue .= "-" . $type[1];
1108 }
1109 // CRM-3157: localise country, region (both have ‘country’ context)
1110 // and state_province (‘province’ context)
1111 switch (TRUE) {
1112 case (!is_object($relDAO)):
1113 $row[$field . '_' . $fldValue] = '';
1114 break;
1115
1116 case in_array('country', $type):
1117 case in_array('world_region', $type):
1118 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
be2fb01f 1119 ['context' => 'country']
1860fab0 1120 );
1121 break;
1122
1123 case in_array('state_province', $type):
1124 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
be2fb01f 1125 ['context' => 'province']
1860fab0 1126 );
1127 break;
1128
1129 default:
1130 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1131 break;
1132 }
1133 }
1134 }
1135 }
1136 elseif (isset($fieldValue) && $fieldValue != '') {
1137 //check for custom data
1138 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
f0d58350 1139 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1860fab0 1140 }
1141 else {
1142 //normal relationship fields
1143 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1144 switch ($relationField) {
1145 case 'country':
1146 case 'world_region':
be2fb01f 1147 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1860fab0 1148 break;
1149
1150 case 'state_province':
be2fb01f 1151 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1860fab0 1152 break;
1153
1154 default:
f0d58350 1155 $row[$relPrefix] = $fieldValue;
1860fab0 1156 break;
1157 }
1158 }
1159 }
1160 else {
1161 // if relation field is empty or null
f0d58350 1162 $row[$relPrefix] = '';
1860fab0 1163 }
1164 }
1165 }
1166
814065a3 1167 /**
1168 * Get the ids that we want to get related contact details for.
1169 *
1170 * @param array $ids
1171 * @param int $exportMode
1172 *
1173 * @return array
1174 */
1175 protected static function getIDsForRelatedContact($ids, $exportMode) {
1176 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
1177 return $ids;
1178 }
1179 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1180 $relIDs = [];
1181 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1182 $dao = CRM_Core_DAO::executeQuery("
1183 SELECT contact_id FROM civicrm_activity_contact
1184 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1185 record_type_id = {$sourceID}
1186 ");
1187
1188 while ($dao->fetch()) {
1189 $relIDs[] = $dao->contact_id;
1190 }
1191 return $relIDs;
1192 }
1193 $component = self::exportComponent($exportMode);
1194
1195 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
1196 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
1197 }
1198 else {
1199 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
1200 }
1201 }
1202
44f8f95c 1203 /**
1204 * @param $selectAll
1205 * @param $ids
439355f5 1206 * @param \CRM_Export_BAO_ExportProcessor $processor
44f8f95c 1207 * @param $componentTable
44f8f95c 1208 */
ce12a9e0 1209 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
be2fb01f 1210 $allRelContactArray = $relationQuery = [];
439355f5 1211 $queryMode = $processor->getQueryMode();
1212 $exportMode = $processor->getExportMode();
44f8f95c 1213
ce12a9e0 1214 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
be2fb01f 1215 $allRelContactArray[$relationshipKey] = [];
ce12a9e0 1216 // build Query for each relationship
1217 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1218 NULL, FALSE, FALSE, $queryMode
1219 );
1220 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1221
1222 list($id, $direction) = explode('_', $relationshipKey, 2);
1223 // identify the relationship direction
1224 $contactA = 'contact_id_a';
1225 $contactB = 'contact_id_b';
1226 if ($direction == 'b_a') {
1227 $contactA = 'contact_id_b';
1228 $contactB = 'contact_id_a';
1229 }
1230 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
1231
1232 $relationshipJoin = $relationshipClause = '';
1233 if (!$selectAll && $componentTable) {
1234 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1235 }
1236 elseif (!empty($relIDs)) {
1237 $relID = implode(',', $relIDs);
1238 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1239 }
44f8f95c 1240
ce12a9e0 1241 $relationFrom = " {$relationFrom}
1242 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1243 {$relationshipJoin} ";
1244
1245 //check for active relationship status only
1246 $today = date('Ymd');
1247 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1248 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
6f5824c1 1249 CRM_Core_DAO::disableFullGroupByMode();
ce12a9e0 1250 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
6f5824c1 1251 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
ce12a9e0 1252
1253 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
6f5824c1 1254 CRM_Core_DAO::reenableFullGroupByMode();
1255
ce12a9e0 1256 while ($allRelContactDAO->fetch()) {
1257 $relationQuery->convertToPseudoNames($allRelContactDAO);
1258 $row = [];
1259 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1260 self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1261 foreach (array_keys($relationReturnProperties) as $property) {
1262 if ($property === 'location') {
1263 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1264 // $processor->setRelationshipValue from fetchRelationshipDetails
1265 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1266 foreach (array_keys($locationValues) as $locationValue) {
1267 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1268 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
1269 }
1270 }
1271 }
1272 else {
1273 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
1274 }
44f8f95c 1275 }
44f8f95c 1276 }
1277 }
44f8f95c 1278 }
1279
6a488035 1280}