Merge pull request #13473 from deb1990/C51-384-add-case-token-in-email
[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 $property
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 $component
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 $groupBy
124 * Group By Clause
125 */
126 public static function getGroupBy($processor, $returnProperties, $query) {
127 $groupBy = '';
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 = array('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 ' . $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 = array(),
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 = array();
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'] = array();
280 $tempColumns = array('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'] = array();
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 = array('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 self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
338
339 // make sure the groups stuff is included only if specifically specified
340 // by the fields param (CRM-1969), else we limit the contacts outputted to only
341 // ones that are part of a group
342 if (!empty($returnProperties['groups'])) {
343 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
344 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
345 // total hack for export, CRM-3618
346 $from = str_replace($oldClause,
347 $newClause,
348 $from
349 );
350 }
351
352 if (!$selectAll && $componentTable) {
353 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
354 }
355 elseif ($componentClause) {
356 if (empty($where)) {
357 $where = "WHERE $componentClause";
358 }
359 else {
360 $where .= " AND $componentClause";
361 }
362 }
363
364 // CRM-13982 - check if is deleted
365 $excludeTrashed = TRUE;
366 foreach ($params as $value) {
367 if ($value[0] == 'contact_is_deleted') {
368 $excludeTrashed = FALSE;
369 }
370 }
371 $trashClause = $excludeTrashed ? "contact_a.is_deleted != 1" : "( 1 )";
372
373 if (empty($where)) {
374 $where = "WHERE $trashClause";
375 }
376 else {
377 $where .= " AND $trashClause";
378 }
379
380 $queryString = "$select $from $where $having";
381
382 $groupBy = self::getGroupBy($processor, $returnProperties, $query);
383
384 $queryString .= $groupBy;
385
386 if ($order) {
387 // always add contact_a.id to the ORDER clause
388 // so the order is deterministic
389 //CRM-15301
390 if (strpos('contact_a.id', $order) === FALSE) {
391 $order .= ", contact_a.id";
392 }
393
394 list($field, $dir) = explode(' ', $order, 2);
395 $field = trim($field);
396 if (!empty($returnProperties[$field])) {
397 //CRM-15301
398 $queryString .= " ORDER BY $order";
399 }
400 }
401
402 $addPaymentHeader = FALSE;
403
404 list($outputColumns, $metadata) = self::getExportStructureArrays($returnProperties, $processor);
405
406 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
407 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
408 // test exists covering this...
409 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
410 $processor->setColumnAsCalculationOnly($field);
411 }
412 }
413
414 $paymentDetails = [];
415 if ($processor->isExportPaymentFields()) {
416 // get payment related in for event and members
417 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
418 //get all payment headers.
419 // If we haven't selected specific payment fields, load in all the
420 // payment headers.
421 if (!$processor->isExportSpecifiedPaymentFields()) {
422 if (!empty($paymentDetails)) {
423 $addPaymentHeader = TRUE;
424 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
425 $processor->addOutputSpecification($paymentField);
426 }
427 }
428 }
429 }
430
431 $componentDetails = array();
432
433 $rowCount = self::EXPORT_ROW_COUNT;
434 $offset = 0;
435 // we write to temp table often to avoid using too much memory
436 $tempRowCount = 100;
437
438 $count = -1;
439
440 $headerRows = $processor->getHeaderRows();
441 $sqlColumns = $processor->getSQLColumns();
442 $exportTempTable = self::createTempTable($sqlColumns);
443 $limitReached = FALSE;
444
445 while (!$limitReached) {
446 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
447 CRM_Core_DAO::disableFullGroupByMode();
448 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
449 CRM_Core_DAO::reenableFullGroupByMode();
450 // If this is less than our limit by the end of the iteration we do not need to run the query again to
451 // check if some remain.
452 $rowsThisIteration = 0;
453
454 while ($iterationDAO->fetch()) {
455 $count++;
456 $rowsThisIteration++;
457 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
458 if ($row === FALSE) {
459 continue;
460 }
461
462 // add component info
463 // write the row to a file
464 $componentDetails[] = $row;
465
466 // output every $tempRowCount rows
467 if ($count % $tempRowCount == 0) {
468 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
469 $componentDetails = array();
470 }
471 }
472 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
473 $limitReached = TRUE;
474 }
475 $offset += $rowCount;
476 }
477
478 if ($exportTempTable) {
479 self::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
480
481 // do merge same address and merge same household processing
482 if ($mergeSameAddress) {
483 self::mergeSameAddress($exportTempTable, $sqlColumns, $exportParams);
484 }
485
486 // call export hook
487 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
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($exportTempTable, $headerRows, $sqlColumns, $processor);
493 }
494 else {
495 // return tableName sqlColumns headerRows in test context
496 return array($exportTempTable, $sqlColumns, $headerRows, $processor);
497 }
498
499 // delete the export temp table and component table
500 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
501 CRM_Core_DAO::executeQuery($sql);
502 CRM_Core_DAO::reenableFullGroupByMode();
503 CRM_Utils_System::civiExit();
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 = array();
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 = array();
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 string $tableName
603 * @param $details
604 * @param $sqlColumns
605 */
606 public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
607 if (empty($details)) {
608 return;
609 }
610
611 $sql = "
612 SELECT max(id)
613 FROM $tableName
614 ";
615
616 $id = CRM_Core_DAO::singleValueQuery($sql);
617 if (!$id) {
618 $id = 0;
619 }
620
621 $sqlClause = array();
622
623 foreach ($details as $row) {
624 $id++;
625 $valueString = array($id);
626 foreach ($row as $value) {
627 if (empty($value)) {
628 $valueString[] = "''";
629 }
630 else {
631 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
632 }
633 }
634 $sqlClause[] = '(' . implode(',', $valueString) . ')';
635 }
636
637 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
638
639 $sqlValueString = implode(",\n", $sqlClause);
640
641 $sql = "
642 INSERT INTO $tableName $sqlColumnString
643 VALUES $sqlValueString
644 ";
645 CRM_Core_DAO::executeQuery($sql);
646 }
647
648 /**
649 * @param $sqlColumns
650 *
651 * @return string
652 */
653 public static function createTempTable($sqlColumns) {
654 //creating a temporary table for the search result that need be exported
655 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export')->getName();
656
657 // also create the sql table
658 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
659 CRM_Core_DAO::executeQuery($sql);
660
661 $sql = "
662 CREATE TABLE {$exportTempTable} (
663 id int unsigned NOT NULL AUTO_INCREMENT,
664 ";
665 $sql .= implode(",\n", array_values($sqlColumns));
666
667 $sql .= ",
668 PRIMARY KEY ( id )
669 ";
670 // add indexes for street_address and household_name if present
671 $addIndices = array(
672 'street_address',
673 'household_name',
674 'civicrm_primary_id',
675 );
676
677 foreach ($addIndices as $index) {
678 if (isset($sqlColumns[$index])) {
679 $sql .= ",
680 INDEX index_{$index}( $index )
681 ";
682 }
683 }
684
685 $sql .= "
686 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
687 ";
688
689 CRM_Core_DAO::executeQuery($sql);
690 return $exportTempTable;
691 }
692
693 /**
694 * @param string $tableName
695 * @param $sqlColumns
696 * @param array $exportParams
697 */
698 public static function mergeSameAddress($tableName, &$sqlColumns, $exportParams) {
699 // check if any records are present based on if they have used shared address feature,
700 // and not based on if city / state .. matches.
701 $sql = "
702 SELECT r1.id as copy_id,
703 r1.civicrm_primary_id as copy_contact_id,
704 r1.addressee as copy_addressee,
705 r1.addressee_id as copy_addressee_id,
706 r1.postal_greeting as copy_postal_greeting,
707 r1.postal_greeting_id as copy_postal_greeting_id,
708 r2.id as master_id,
709 r2.civicrm_primary_id as master_contact_id,
710 r2.postal_greeting as master_postal_greeting,
711 r2.postal_greeting_id as master_postal_greeting_id,
712 r2.addressee as master_addressee,
713 r2.addressee_id as master_addressee_id
714 FROM $tableName r1
715 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
716 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
717 ORDER BY r1.id";
718 $linkedMerge = self::_buildMasterCopyArray($sql, $exportParams, TRUE);
719
720 // find all the records that have the same street address BUT not in a household
721 // require match on city and state as well
722 $sql = "
723 SELECT r1.id as master_id,
724 r1.civicrm_primary_id as master_contact_id,
725 r1.postal_greeting as master_postal_greeting,
726 r1.postal_greeting_id as master_postal_greeting_id,
727 r1.addressee as master_addressee,
728 r1.addressee_id as master_addressee_id,
729 r2.id as copy_id,
730 r2.civicrm_primary_id as copy_contact_id,
731 r2.postal_greeting as copy_postal_greeting,
732 r2.postal_greeting_id as copy_postal_greeting_id,
733 r2.addressee as copy_addressee,
734 r2.addressee_id as copy_addressee_id
735 FROM $tableName r1
736 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
737 r1.city = r2.city AND
738 r1.state_province_id = r2.state_province_id )
739 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
740 AND ( r2.household_name IS NULL OR r2.household_name = '' )
741 AND ( r1.street_address != '' )
742 AND r2.id > r1.id
743 ORDER BY r1.id
744 ";
745 $merge = self::_buildMasterCopyArray($sql, $exportParams);
746
747 // unset ids from $merge already present in $linkedMerge
748 foreach ($linkedMerge as $masterID => $values) {
749 $keys = array($masterID);
750 $keys = array_merge($keys, array_keys($values['copy']));
751 foreach ($merge as $mid => $vals) {
752 if (in_array($mid, $keys)) {
753 unset($merge[$mid]);
754 }
755 else {
756 foreach ($values['copy'] as $copyId) {
757 if (in_array($copyId, $keys)) {
758 unset($merge[$mid]['copy'][$copyId]);
759 }
760 }
761 }
762 }
763 }
764 $merge = $merge + $linkedMerge;
765
766 foreach ($merge as $masterID => $values) {
767 $sql = "
768 UPDATE $tableName
769 SET addressee = %1, postal_greeting = %2, email_greeting = %3
770 WHERE id = %4
771 ";
772 $params = array(
773 1 => array($values['addressee'], 'String'),
774 2 => array($values['postalGreeting'], 'String'),
775 3 => array($values['emailGreeting'], 'String'),
776 4 => array($masterID, 'Integer'),
777 );
778 CRM_Core_DAO::executeQuery($sql, $params);
779
780 // delete all copies
781 $deleteIDs = array_keys($values['copy']);
782 $deleteIDString = implode(',', $deleteIDs);
783 $sql = "
784 DELETE FROM $tableName
785 WHERE id IN ( $deleteIDString )
786 ";
787 CRM_Core_DAO::executeQuery($sql);
788 }
789
790 // unset temporary columns that were added for postal mailing format
791 // @todo - this part is pretty close to ready to be removed....
792 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
793 $unsetKeys = array_keys($sqlColumns);
794 foreach ($unsetKeys as $headerKey => $sqlColKey) {
795 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
796 unset($sqlColumns[$sqlColKey]);
797 }
798 }
799 }
800 }
801
802 /**
803 * @param int $contactId
804 * @param array $exportParams
805 *
806 * @return array
807 */
808 public static function _replaceMergeTokens($contactId, $exportParams) {
809 $greetings = array();
810 $contact = NULL;
811
812 $greetingFields = array(
813 'postal_greeting',
814 'addressee',
815 );
816 foreach ($greetingFields as $greeting) {
817 if (!empty($exportParams[$greeting])) {
818 $greetingLabel = $exportParams[$greeting];
819 if (empty($contact)) {
820 $values = array(
821 'id' => $contactId,
822 'version' => 3,
823 );
824 $contact = civicrm_api('contact', 'get', $values);
825
826 if (!empty($contact['is_error'])) {
827 return $greetings;
828 }
829 $contact = $contact['values'][$contact['id']];
830 }
831
832 $tokens = array('contact' => $greetingLabel);
833 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
834 }
835 }
836 return $greetings;
837 }
838
839 /**
840 * The function unsets static part of the string, if token is the dynamic part.
841 *
842 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
843 * i.e 'Hello Alan' => converted to => 'Alan'
844 *
845 * @param string $parsedString
846 * @param string $defaultGreeting
847 * @param bool $addressMergeGreetings
848 * @param string $greetingType
849 *
850 * @return mixed
851 */
852 public static function _trimNonTokens(
853 &$parsedString, $defaultGreeting,
854 $addressMergeGreetings, $greetingType = 'postal_greeting'
855 ) {
856 if (!empty($addressMergeGreetings[$greetingType])) {
857 $greetingLabel = $addressMergeGreetings[$greetingType];
858 }
859 $greetingLabel = empty($greetingLabel) ? $defaultGreeting : $greetingLabel;
860
861 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
862 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
863 foreach ($stringsToBeReplaced as $key => $string) {
864 // to keep one space
865 $stringsToBeReplaced[$key] = ltrim($string);
866 }
867 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
868
869 return $parsedString;
870 }
871
872 /**
873 * @param $sql
874 * @param array $exportParams
875 * @param bool $sharedAddress
876 *
877 * @return array
878 */
879 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
880 static $contactGreetingTokens = array();
881
882 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
883 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
884
885 $merge = $parents = array();
886 $dao = CRM_Core_DAO::executeQuery($sql);
887
888 while ($dao->fetch()) {
889 $masterID = $dao->master_id;
890 $copyID = $dao->copy_id;
891 $masterPostalGreeting = $dao->master_postal_greeting;
892 $masterAddressee = $dao->master_addressee;
893 $copyAddressee = $dao->copy_addressee;
894
895 if (!$sharedAddress) {
896 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
897 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
898 }
899 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
900 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
901 );
902 $masterAddressee = CRM_Utils_Array::value('addressee',
903 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
904 );
905
906 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
907 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
908 }
909 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
910 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
911 );
912 $copyAddressee = CRM_Utils_Array::value('addressee',
913 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
914 );
915 }
916
917 if (!isset($merge[$masterID])) {
918 // check if this is an intermediate child
919 // this happens if there are 3 or more matches a,b, c
920 // the above query will return a, b / a, c / b, c
921 // we might be doing a bit more work, but for now its ok, unless someone
922 // knows how to fix the query above
923 if (isset($parents[$masterID])) {
924 $masterID = $parents[$masterID];
925 }
926 else {
927 $merge[$masterID] = array(
928 'addressee' => $masterAddressee,
929 'copy' => array(),
930 'postalGreeting' => $masterPostalGreeting,
931 );
932 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
933 }
934 }
935 $parents[$copyID] = $masterID;
936
937 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
938
939 if (!empty($exportParams['postal_greeting_other']) &&
940 count($merge[$masterID]['copy']) >= 1
941 ) {
942 // use static greetings specified if no of contacts > 2
943 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
944 }
945 elseif ($copyPostalGreeting) {
946 self::_trimNonTokens($copyPostalGreeting,
947 $postalOptions[$dao->copy_postal_greeting_id],
948 $exportParams
949 );
950 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
951 // if there happens to be a duplicate, remove it
952 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
953 }
954
955 if (!empty($exportParams['addressee_other']) &&
956 count($merge[$masterID]['copy']) >= 1
957 ) {
958 // use static greetings specified if no of contacts > 2
959 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
960 }
961 elseif ($copyAddressee) {
962 self::_trimNonTokens($copyAddressee,
963 $addresseeOptions[$dao->copy_addressee_id],
964 $exportParams, 'addressee'
965 );
966 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
967 }
968 }
969 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
970 }
971
972 return $merge;
973 }
974
975 /**
976 * @param $exportTempTable
977 * @param $headerRows
978 * @param $sqlColumns
979 * @param \CRM_Export_BAO_ExportProcessor $processor
980 */
981 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor) {
982 $exportMode = $processor->getExportMode();
983 $writeHeader = TRUE;
984 $offset = 0;
985 $limit = self::EXPORT_ROW_COUNT;
986
987 $query = "SELECT * FROM $exportTempTable";
988
989 while (1) {
990 $limitQuery = $query . "
991 LIMIT $offset, $limit
992 ";
993 $dao = CRM_Core_DAO::executeQuery($limitQuery);
994
995 if ($dao->N <= 0) {
996 break;
997 }
998
999 $componentDetails = array();
1000 while ($dao->fetch()) {
1001 $row = array();
1002
1003 foreach ($sqlColumns as $column => $dontCare) {
1004 $row[$column] = $dao->$column;
1005 }
1006 $componentDetails[] = $row;
1007 }
1008 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
1009 $headerRows,
1010 $componentDetails,
1011 NULL,
1012 $writeHeader
1013 );
1014
1015 $writeHeader = FALSE;
1016 $offset += $limit;
1017 }
1018 }
1019
1020 /**
1021 * Build componentPayment fields.
1022 *
1023 * This is no longer used by export but BAO_Mapping still calls it & we
1024 * should find a generic way to handle this or move this to that class.
1025 *
1026 * @deprecated
1027 */
1028 public static function componentPaymentFields() {
1029 static $componentPaymentFields;
1030 if (!isset($componentPaymentFields)) {
1031 $componentPaymentFields = array(
1032 'componentPaymentField_total_amount' => ts('Total Amount'),
1033 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1034 'componentPaymentField_received_date' => ts('Date Received'),
1035 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1036 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1037 );
1038 }
1039 return $componentPaymentFields;
1040 }
1041
1042 /**
1043 * Get the various arrays that we use to structure our output.
1044 *
1045 * The extraction of these has been moved to a separate function for clarity and so that
1046 * tests can be added - in particular on the $outputHeaders array.
1047 *
1048 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1049 * as a step on the refactoring path rather than how it should be.
1050 *
1051 * @param array $returnProperties
1052 * @param \CRM_Export_BAO_ExportProcessor $processor
1053 *
1054 * @return array
1055 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1056 * alias for the field generated by BAO_Query object.
1057 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1058 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1059 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1060 * I'm too embarassed to discuss here.
1061 * The keys need
1062 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1063 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1064 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1065 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1066 * - a) the function used is more efficient or
1067 * - b) this code is old & outdated. Submit your answers to circular bin or better
1068 * yet find a way to comment them for posterity.
1069 */
1070 public static function getExportStructureArrays($returnProperties, $processor) {
1071 $outputColumns = $metadata = array();
1072 $queryFields = $processor->getQueryFields();
1073 foreach ($returnProperties as $key => $value) {
1074 if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
1075 $outputColumns[$key] = $value;
1076 $processor->addOutputSpecification($key);
1077 }
1078 elseif ($processor->isRelationshipTypeKey($key)) {
1079 $outputColumns[$key] = $value;
1080 foreach ($value as $relationField => $relationValue) {
1081 // below block is same as primary block (duplicate)
1082 if (isset($queryFields[$relationField]['title'])) {
1083 $processor->addOutputSpecification($relationField, $key);
1084 }
1085 elseif (is_array($relationValue) && $relationField == 'location') {
1086 // fix header for location type case
1087 foreach ($relationValue as $ltype => $val) {
1088 foreach (array_keys($val) as $fld) {
1089 $type = explode('-', $fld);
1090 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
1091 }
1092 }
1093 }
1094 }
1095 }
1096 else {
1097 foreach ($value as $locationType => $locationFields) {
1098 foreach (array_keys($locationFields) as $locationFieldName) {
1099 $type = explode('-', $locationFieldName);
1100
1101 $actualDBFieldName = $type[0];
1102 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
1103
1104 if (!empty($type[1])) {
1105 $daoFieldName .= "-" . $type[1];
1106 }
1107 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
1108 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
1109 $outputColumns[$daoFieldName] = TRUE;
1110 }
1111 }
1112 }
1113 }
1114 return array($outputColumns, $metadata);
1115 }
1116
1117 /**
1118 * Get the values of linked household contact.
1119 *
1120 * @param CRM_Core_DAO $relDAO
1121 * @param array $value
1122 * @param string $field
1123 * @param array $row
1124 */
1125 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1126 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
1127 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
1128 $i18n = CRM_Core_I18n::singleton();
1129 $field = $field . '_';
1130
1131 foreach ($value as $relationField => $relationValue) {
1132 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1133 $fieldValue = $relDAO->$relationField;
1134 if ($relationField == 'phone_type_id') {
1135 $fieldValue = $phoneTypes[$relationValue];
1136 }
1137 elseif ($relationField == 'provider_id') {
1138 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
1139 }
1140 // CRM-13995
1141 elseif (is_object($relDAO) && in_array($relationField, array(
1142 'email_greeting',
1143 'postal_greeting',
1144 'addressee',
1145 ))
1146 ) {
1147 //special case for greeting replacement
1148 $fldValue = "{$relationField}_display";
1149 $fieldValue = $relDAO->$fldValue;
1150 }
1151 }
1152 elseif (is_object($relDAO) && $relationField == 'state_province') {
1153 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
1154 }
1155 elseif (is_object($relDAO) && $relationField == 'country') {
1156 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
1157 }
1158 else {
1159 $fieldValue = '';
1160 }
1161 $relPrefix = $field . $relationField;
1162
1163 if (is_object($relDAO) && $relationField == 'id') {
1164 $row[$relPrefix] = $relDAO->contact_id;
1165 }
1166 elseif (is_array($relationValue) && $relationField == 'location') {
1167 foreach ($relationValue as $ltype => $val) {
1168 // If the location name has a space in it the we need to handle that. This
1169 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1170 // improve it should be secure in the knowled it will be caught.
1171 $ltype = str_replace(' ', '_', $ltype);
1172 foreach (array_keys($val) as $fld) {
1173 $type = explode('-', $fld);
1174 $fldValue = "{$ltype}-" . $type[0];
1175 if (!empty($type[1])) {
1176 $fldValue .= "-" . $type[1];
1177 }
1178 // CRM-3157: localise country, region (both have ‘country’ context)
1179 // and state_province (‘province’ context)
1180 switch (TRUE) {
1181 case (!is_object($relDAO)):
1182 $row[$field . '_' . $fldValue] = '';
1183 break;
1184
1185 case in_array('country', $type):
1186 case in_array('world_region', $type):
1187 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1188 array('context' => 'country')
1189 );
1190 break;
1191
1192 case in_array('state_province', $type):
1193 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1194 array('context' => 'province')
1195 );
1196 break;
1197
1198 default:
1199 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1200 break;
1201 }
1202 }
1203 }
1204 }
1205 elseif (isset($fieldValue) && $fieldValue != '') {
1206 //check for custom data
1207 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
1208 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1209 }
1210 else {
1211 //normal relationship fields
1212 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1213 switch ($relationField) {
1214 case 'country':
1215 case 'world_region':
1216 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1217 break;
1218
1219 case 'state_province':
1220 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1221 break;
1222
1223 default:
1224 $row[$relPrefix] = $fieldValue;
1225 break;
1226 }
1227 }
1228 }
1229 else {
1230 // if relation field is empty or null
1231 $row[$relPrefix] = '';
1232 }
1233 }
1234 }
1235
1236 /**
1237 * Get the ids that we want to get related contact details for.
1238 *
1239 * @param array $ids
1240 * @param int $exportMode
1241 *
1242 * @return array
1243 */
1244 protected static function getIDsForRelatedContact($ids, $exportMode) {
1245 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
1246 return $ids;
1247 }
1248 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1249 $relIDs = [];
1250 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1251 $dao = CRM_Core_DAO::executeQuery("
1252 SELECT contact_id FROM civicrm_activity_contact
1253 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1254 record_type_id = {$sourceID}
1255 ");
1256
1257 while ($dao->fetch()) {
1258 $relIDs[] = $dao->contact_id;
1259 }
1260 return $relIDs;
1261 }
1262 $component = self::exportComponent($exportMode);
1263
1264 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
1265 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
1266 }
1267 else {
1268 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
1269 }
1270 }
1271
1272 /**
1273 * @param $selectAll
1274 * @param $ids
1275 * @param \CRM_Export_BAO_ExportProcessor $processor
1276 * @param $componentTable
1277 */
1278 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1279 $allRelContactArray = $relationQuery = array();
1280 $queryMode = $processor->getQueryMode();
1281 $exportMode = $processor->getExportMode();
1282
1283 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1284 $allRelContactArray[$relationshipKey] = array();
1285 // build Query for each relationship
1286 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1287 NULL, FALSE, FALSE, $queryMode
1288 );
1289 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1290
1291 list($id, $direction) = explode('_', $relationshipKey, 2);
1292 // identify the relationship direction
1293 $contactA = 'contact_id_a';
1294 $contactB = 'contact_id_b';
1295 if ($direction == 'b_a') {
1296 $contactA = 'contact_id_b';
1297 $contactB = 'contact_id_a';
1298 }
1299 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
1300
1301 $relationshipJoin = $relationshipClause = '';
1302 if (!$selectAll && $componentTable) {
1303 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1304 }
1305 elseif (!empty($relIDs)) {
1306 $relID = implode(',', $relIDs);
1307 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1308 }
1309
1310 $relationFrom = " {$relationFrom}
1311 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1312 {$relationshipJoin} ";
1313
1314 //check for active relationship status only
1315 $today = date('Ymd');
1316 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1317 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1318 CRM_Core_DAO::disableFullGroupByMode();
1319 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1320 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1321
1322 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
1323 CRM_Core_DAO::reenableFullGroupByMode();
1324
1325 while ($allRelContactDAO->fetch()) {
1326 $relationQuery->convertToPseudoNames($allRelContactDAO);
1327 $row = [];
1328 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1329 self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1330 foreach (array_keys($relationReturnProperties) as $property) {
1331 if ($property === 'location') {
1332 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1333 // $processor->setRelationshipValue from fetchRelationshipDetails
1334 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1335 foreach (array_keys($locationValues) as $locationValue) {
1336 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1337 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
1338 }
1339 }
1340 }
1341 else {
1342 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
1343 }
1344 }
1345 }
1346 }
1347 }
1348
1349 }