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