Merge pull request #14852 from pradpnayak/SttingsTitle
[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 Export component
46 *
47 * @param int $exportMode
48 * Export mode.
49 *
50 * @return string
51 * CiviCRM Export Component
52 */
53 public static function exportComponent($exportMode) {
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
78 /**
79 * Get the list the export fields.
80 *
81 * @param int $selectAll
82 * User preference while export.
83 * @param array $ids
84 * Contact ids.
85 * @param array $params
86 * Associated array of fields.
87 * @param string $order
88 * Order by clause.
89 * @param array $fields
90 * Associated array of fields.
91 * @param array $moreReturnProperties
92 * Additional return fields.
93 * @param int $exportMode
94 * Export mode.
95 * @param string $componentClause
96 * Component clause.
97 * @param string $componentTable
98 * Component table.
99 * @param bool $mergeSameAddress
100 * Merge records if they have same address.
101 * @param bool $mergeSameHousehold
102 * Merge records if they belong to the same household.
103 *
104 * @param array $exportParams
105 * @param string $queryOperator
106 *
107 * @return array|null
108 * An array can be requested from within a unit test.
109 *
110 * @throws \CRM_Core_Exception
111 */
112 public static function exportComponents(
113 $selectAll,
114 $ids,
115 $params,
116 $order = NULL,
117 $fields = NULL,
118 $moreReturnProperties = NULL,
119 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
120 $componentClause = NULL,
121 $componentTable = NULL,
122 $mergeSameAddress = FALSE,
123 $mergeSameHousehold = FALSE,
124 $exportParams = [],
125 $queryOperator = 'AND'
126 ) {
127
128 $isPostalOnly = (
129 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
130 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
131 );
132
133 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
134 // If an Additional Group is selected, then all contacts in that group are
135 // added to the export set (filtering out duplicates).
136 // Really - the calling function could do this ... just saying
137 // @todo take a whip to the calling function.
138 CRM_Core_DAO::executeQuery("
139 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"
140 );
141 }
142 // rectify params to what proximity search expects if there is a value for prox_distance
143 // CRM-7021
144 // @todo - move this back to the calling functions
145 if (!empty($params)) {
146 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
147 }
148 // @todo everything from this line up should go back to the calling functions.
149 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress, $exportParams);
150 if ($moreReturnProperties) {
151 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
152 }
153 $processor->setComponentTable($componentTable);
154 $processor->setComponentClause($componentClause);
155
156 list($query, $queryString) = $processor->runQuery($params, $order);
157
158 // This perhaps only needs calling when $mergeSameHousehold == 1
159 self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
160
161 $addPaymentHeader = FALSE;
162
163 list($outputColumns, $metadata) = $processor->getExportStructureArrays();
164
165 if ($processor->isMergeSameAddress()) {
166 foreach (array_keys($processor->getAdditionalFieldsForSameAddressMerge()) as $field) {
167 $processor->setColumnAsCalculationOnly($field);
168 }
169 }
170
171 $paymentDetails = [];
172 if ($processor->isExportPaymentFields()) {
173 // get payment related in for event and members
174 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
175 //get all payment headers.
176 // If we haven't selected specific payment fields, load in all the
177 // payment headers.
178 if (!$processor->isExportSpecifiedPaymentFields()) {
179 if (!empty($paymentDetails)) {
180 $addPaymentHeader = TRUE;
181 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
182 $processor->addOutputSpecification($paymentField);
183 }
184 }
185 }
186 }
187
188 $componentDetails = [];
189
190 $rowCount = self::EXPORT_ROW_COUNT;
191 $offset = 0;
192 // we write to temp table often to avoid using too much memory
193 $tempRowCount = 100;
194
195 $count = -1;
196
197 $headerRows = $processor->getHeaderRows();
198 $sqlColumns = $processor->getSQLColumns();
199 $processor->setTemporaryTable(self::createTempTable($sqlColumns));
200 $limitReached = FALSE;
201
202 while (!$limitReached) {
203 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
204 CRM_Core_DAO::disableFullGroupByMode();
205 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
206 CRM_Core_DAO::reenableFullGroupByMode();
207 // If this is less than our limit by the end of the iteration we do not need to run the query again to
208 // check if some remain.
209 $rowsThisIteration = 0;
210
211 while ($iterationDAO->fetch()) {
212 $count++;
213 $rowsThisIteration++;
214 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader);
215 if ($row === FALSE) {
216 continue;
217 }
218
219 // add component info
220 // write the row to a file
221 $componentDetails[] = $row;
222
223 // output every $tempRowCount rows
224 if ($count % $tempRowCount == 0) {
225 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
226 $componentDetails = [];
227 }
228 }
229 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
230 $limitReached = TRUE;
231 }
232 $offset += $rowCount;
233 }
234
235 if ($processor->getTemporaryTable()) {
236 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
237
238 // do merge same address and merge same household processing
239 if ($mergeSameAddress) {
240 $processor->mergeSameAddress();
241 }
242
243 // call export hook
244 $table = $processor->getTemporaryTable();
245 CRM_Utils_Hook::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
246 if ($table !== $processor->getTemporaryTable()) {
247 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
248 $processor->setTemporaryTable($table);
249 }
250
251 // In order to be able to write a unit test against this function we need to suppress
252 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
253 if (empty($exportParams['suppress_csv_for_testing'])) {
254 self::writeCSVFromTable($headerRows, $sqlColumns, $processor);
255 }
256 else {
257 // return tableName sqlColumns headerRows in test context
258 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
259 }
260
261 // delete the export temp table and component table
262 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
263 CRM_Core_DAO::executeQuery($sql);
264 CRM_Core_DAO::reenableFullGroupByMode();
265 CRM_Utils_System::civiExit(0, ['processor' => $processor]);
266 }
267 else {
268 CRM_Core_DAO::reenableFullGroupByMode();
269 throw new CRM_Core_Exception(ts('No records to export'));
270 }
271 }
272
273 /**
274 * Handle import error file creation.
275 */
276 public static function invoke() {
277 $type = CRM_Utils_Request::retrieve('type', 'Positive');
278 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
279 if (empty($parserName) || empty($type)) {
280 return;
281 }
282
283 // clean and ensure parserName is a valid string
284 $parserName = CRM_Utils_String::munge($parserName);
285 $parserClass = explode('_', $parserName);
286
287 // make sure parserClass is in the CRM namespace and
288 // at least 3 levels deep
289 if ($parserClass[0] == 'CRM' &&
290 count($parserClass) >= 3
291 ) {
292 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
293 // ensure the functions exists
294 if (method_exists($parserName, 'errorFileName') &&
295 method_exists($parserName, 'saveFileName')
296 ) {
297 $errorFileName = $parserName::errorFileName($type);
298 $saveFileName = $parserName::saveFileName($type);
299 if (!empty($errorFileName) && !empty($saveFileName)) {
300 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
301 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
302 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
303 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
304 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
305
306 readfile($errorFileName);
307 }
308 }
309 }
310 CRM_Utils_System::civiExit();
311 }
312
313 /**
314 * @param $customSearchClass
315 * @param $formValues
316 * @param $order
317 */
318 public static function exportCustom($customSearchClass, $formValues, $order) {
319 $ext = CRM_Extension_System::singleton()->getMapper();
320 if (!$ext->isExtensionClass($customSearchClass)) {
321 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
322 }
323 else {
324 require_once $ext->classToPath($customSearchClass);
325 }
326 $search = new $customSearchClass($formValues);
327
328 $includeContactIDs = FALSE;
329 if ($formValues['radio_ts'] == 'ts_sel') {
330 $includeContactIDs = TRUE;
331 }
332
333 $sql = $search->all(0, 0, $order, $includeContactIDs);
334
335 $columns = $search->columns();
336
337 $header = array_keys($columns);
338 $fields = array_values($columns);
339
340 $rows = [];
341 $dao = CRM_Core_DAO::executeQuery($sql);
342 $alterRow = FALSE;
343 if (method_exists($search, 'alterRow')) {
344 $alterRow = TRUE;
345 }
346 while ($dao->fetch()) {
347 $row = [];
348
349 foreach ($fields as $field) {
350 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
351 $row[$field] = $dao->$unqualified_field;
352 }
353 if ($alterRow) {
354 $search->alterRow($row);
355 }
356 $rows[] = $row;
357 }
358
359 CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
360 CRM_Utils_System::civiExit();
361 }
362
363 /**
364 * @param \CRM_Export_BAO_ExportProcessor $processor
365 * @param $details
366 * @param $sqlColumns
367 */
368 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
369 $tableName = $processor->getTemporaryTable();
370 if (empty($details)) {
371 return;
372 }
373
374 $sql = "
375 SELECT max(id)
376 FROM $tableName
377 ";
378
379 $id = CRM_Core_DAO::singleValueQuery($sql);
380 if (!$id) {
381 $id = 0;
382 }
383
384 $sqlClause = [];
385
386 foreach ($details as $row) {
387 $id++;
388 $valueString = [$id];
389 foreach ($row as $value) {
390 if (empty($value)) {
391 $valueString[] = "''";
392 }
393 else {
394 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
395 }
396 }
397 $sqlClause[] = '(' . implode(',', $valueString) . ')';
398 }
399 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
400 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
401
402 $sqlValueString = implode(",\n", $sqlClause);
403
404 $sql = "
405 INSERT INTO $tableName $sqlColumnString
406 VALUES $sqlValueString
407 ";
408 CRM_Core_DAO::executeQuery($sql);
409 }
410
411 /**
412 * @param $sqlColumns
413 *
414 * @return string
415 */
416 public static function createTempTable($sqlColumns) {
417 //creating a temporary table for the search result that need be exported
418 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
419
420 // also create the sql table
421 $exportTempTable->drop();
422
423 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
424 if (!empty($sqlColumns)) {
425 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
426 }
427
428 $sql .= "\n PRIMARY KEY ( id )";
429
430 // add indexes for street_address and household_name if present
431 $addIndices = [
432 'street_address',
433 'household_name',
434 'civicrm_primary_id',
435 ];
436
437 foreach ($addIndices as $index) {
438 if (isset($sqlColumns[$index])) {
439 $sql .= ",
440 INDEX index_{$index}( $index )
441 ";
442 }
443 }
444
445 $exportTempTable->createWithColumns($sql);
446 return $exportTempTable->getName();
447 }
448
449 /**
450 * @param $headerRows
451 * @param $sqlColumns
452 * @param \CRM_Export_BAO_ExportProcessor $processor
453 */
454 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
455 $exportTempTable = $processor->getTemporaryTable();
456 $writeHeader = TRUE;
457 $offset = 0;
458 $limit = self::EXPORT_ROW_COUNT;
459
460 $query = "SELECT * FROM $exportTempTable";
461
462 while (1) {
463 $limitQuery = $query . "
464 LIMIT $offset, $limit
465 ";
466 $dao = CRM_Core_DAO::executeQuery($limitQuery);
467
468 if ($dao->N <= 0) {
469 break;
470 }
471
472 $componentDetails = [];
473 while ($dao->fetch()) {
474 $row = [];
475
476 foreach (array_keys($processor->getSQLColumns()) as $column) {
477 $row[$column] = $dao->$column;
478 }
479 $componentDetails[] = $row;
480 }
481 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
482 $headerRows,
483 $componentDetails,
484 NULL,
485 $writeHeader
486 );
487
488 $writeHeader = FALSE;
489 $offset += $limit;
490 }
491 }
492
493 /**
494 * Build componentPayment fields.
495 *
496 * This is no longer used by export but BAO_Mapping still calls it & we
497 * should find a generic way to handle this or move this to that class.
498 *
499 * @deprecated
500 */
501 public static function componentPaymentFields() {
502 static $componentPaymentFields;
503 if (!isset($componentPaymentFields)) {
504 $componentPaymentFields = [
505 'componentPaymentField_total_amount' => ts('Total Amount'),
506 'componentPaymentField_contribution_status' => ts('Contribution Status'),
507 'componentPaymentField_received_date' => ts('Date Received'),
508 'componentPaymentField_payment_instrument' => ts('Payment Method'),
509 'componentPaymentField_transaction_id' => ts('Transaction ID'),
510 ];
511 }
512 return $componentPaymentFields;
513 }
514
515 /**
516 * Get the values of linked household contact.
517 *
518 * @param CRM_Core_DAO $relDAO
519 * @param array $value
520 * @param string $field
521 * @param array $row
522 */
523 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
524 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
525 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
526 $i18n = CRM_Core_I18n::singleton();
527 $field = $field . '_';
528
529 foreach ($value as $relationField => $relationValue) {
530 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
531 $fieldValue = $relDAO->$relationField;
532 if ($relationField == 'phone_type_id') {
533 $fieldValue = $phoneTypes[$relationValue];
534 }
535 elseif ($relationField == 'provider_id') {
536 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
537 }
538 // CRM-13995
539 elseif (is_object($relDAO) && in_array($relationField, [
540 'email_greeting',
541 'postal_greeting',
542 'addressee',
543 ])) {
544 //special case for greeting replacement
545 $fldValue = "{$relationField}_display";
546 $fieldValue = $relDAO->$fldValue;
547 }
548 }
549 elseif (is_object($relDAO) && $relationField == 'state_province') {
550 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
551 }
552 elseif (is_object($relDAO) && $relationField == 'country') {
553 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
554 }
555 else {
556 $fieldValue = '';
557 }
558 $relPrefix = $field . $relationField;
559
560 if (is_object($relDAO) && $relationField == 'id') {
561 $row[$relPrefix] = $relDAO->contact_id;
562 }
563 elseif (is_array($relationValue) && $relationField == 'location') {
564 foreach ($relationValue as $ltype => $val) {
565 // If the location name has a space in it the we need to handle that. This
566 // is kinda hacky but specifically covered in the ExportTest so later efforts to
567 // improve it should be secure in the knowled it will be caught.
568 $ltype = str_replace(' ', '_', $ltype);
569 foreach (array_keys($val) as $fld) {
570 $type = explode('-', $fld);
571 $fldValue = "{$ltype}-" . $type[0];
572 if (!empty($type[1])) {
573 $fldValue .= "-" . $type[1];
574 }
575 // CRM-3157: localise country, region (both have ‘country’ context)
576 // and state_province (‘province’ context)
577 switch (TRUE) {
578 case (!is_object($relDAO)):
579 $row[$field . '_' . $fldValue] = '';
580 break;
581
582 case in_array('country', $type):
583 case in_array('world_region', $type):
584 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
585 ['context' => 'country']
586 );
587 break;
588
589 case in_array('state_province', $type):
590 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
591 ['context' => 'province']
592 );
593 break;
594
595 default:
596 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
597 break;
598 }
599 }
600 }
601 }
602 elseif (isset($fieldValue) && $fieldValue != '') {
603 //check for custom data
604 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
605 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
606 }
607 else {
608 //normal relationship fields
609 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
610 switch ($relationField) {
611 case 'country':
612 case 'world_region':
613 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
614 break;
615
616 case 'state_province':
617 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
618 break;
619
620 default:
621 $row[$relPrefix] = $fieldValue;
622 break;
623 }
624 }
625 }
626 else {
627 // if relation field is empty or null
628 $row[$relPrefix] = '';
629 }
630 }
631 }
632
633 /**
634 * Get the ids that we want to get related contact details for.
635 *
636 * @param array $ids
637 * @param int $exportMode
638 *
639 * @return array
640 */
641 protected static function getIDsForRelatedContact($ids, $exportMode) {
642 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
643 return $ids;
644 }
645 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
646 $relIDs = [];
647 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
648 $dao = CRM_Core_DAO::executeQuery("
649 SELECT contact_id FROM civicrm_activity_contact
650 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
651 record_type_id = {$sourceID}
652 ");
653
654 while ($dao->fetch()) {
655 $relIDs[] = $dao->contact_id;
656 }
657 return $relIDs;
658 }
659 $component = self::exportComponent($exportMode);
660
661 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
662 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
663 }
664 else {
665 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
666 }
667 }
668
669 /**
670 * @param $selectAll
671 * @param $ids
672 * @param \CRM_Export_BAO_ExportProcessor $processor
673 * @param $componentTable
674 */
675 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
676 $allRelContactArray = $relationQuery = [];
677 $queryMode = $processor->getQueryMode();
678 $exportMode = $processor->getExportMode();
679
680 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
681 $allRelContactArray[$relationshipKey] = [];
682 // build Query for each relationship
683 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
684 NULL, FALSE, FALSE, $queryMode
685 );
686 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
687
688 list($id, $direction) = explode('_', $relationshipKey, 2);
689 // identify the relationship direction
690 $contactA = 'contact_id_a';
691 $contactB = 'contact_id_b';
692 if ($direction == 'b_a') {
693 $contactA = 'contact_id_b';
694 $contactB = 'contact_id_a';
695 }
696 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
697
698 $relationshipJoin = $relationshipClause = '';
699 if (!$selectAll && $componentTable) {
700 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
701 }
702 elseif (!empty($relIDs)) {
703 $relID = implode(',', $relIDs);
704 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
705 }
706
707 $relationFrom = " {$relationFrom}
708 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
709 {$relationshipJoin} ";
710
711 //check for active relationship status only
712 $today = date('Ymd');
713 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
714 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
715 CRM_Core_DAO::disableFullGroupByMode();
716 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
717 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
718
719 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
720 CRM_Core_DAO::reenableFullGroupByMode();
721
722 while ($allRelContactDAO->fetch()) {
723 $relationQuery->convertToPseudoNames($allRelContactDAO);
724 $row = [];
725 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
726 self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
727 foreach (array_keys($relationReturnProperties) as $property) {
728 if ($property === 'location') {
729 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
730 // $processor->setRelationshipValue from fetchRelationshipDetails
731 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
732 foreach (array_keys($locationValues) as $locationValue) {
733 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
734 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
735 }
736 }
737 }
738 else {
739 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
740 }
741 }
742 }
743 }
744 }
745
746 }