3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
35 * This class contains the functions for Component export
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
42 const EXPORT_ROW_COUNT
= 100000;
45 * Get Export component
47 * @param int $exportMode
51 * CiviCRM Export Component
53 public static function exportComponent($exportMode) {
54 switch ($exportMode) {
55 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
56 $component = 'civicrm_contribution';
59 case CRM_Export_Form_Select
::EVENT_EXPORT
:
60 $component = 'civicrm_participant';
63 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
64 $component = 'civicrm_membership';
67 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
68 $component = 'civicrm_pledge';
71 case CRM_Export_Form_Select
::GRANT_EXPORT
:
72 $component = 'civicrm_grant';
79 * Get Query Group By Clause
80 * @param \CRM_Export_BAO_ExportProcessor $processor
82 * @param object $query
83 * CRM_Contact_BAO_Query
88 public static function getGroupBy($processor, $query) {
90 $returnProperties = $processor->getReturnProperties();
91 $exportMode = $processor->getExportMode();
92 $queryMode = $processor->getQueryMode();
93 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
94 CRM_Utils_Array
::value('notes', $returnProperties) ||
96 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
98 $groupBy = "contact_a.id";
101 switch ($exportMode) {
102 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
103 $groupBy = 'civicrm_contribution.id';
104 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
105 // especial group by when soft credit columns are included
106 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
110 case CRM_Export_Form_Select
::EVENT_EXPORT
:
111 $groupBy = 'civicrm_participant.id';
114 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
115 $groupBy = "civicrm_membership.id";
119 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
120 $groupBy = "civicrm_activity.id ";
123 return $groupBy ?
' GROUP BY ' . implode(', ', (array) $groupBy) : '';
127 * Get the list the export fields.
129 * @param int $selectAll
130 * User preference while export.
133 * @param array $params
134 * Associated array of fields.
135 * @param string $order
137 * @param array $fields
138 * Associated array of fields.
139 * @param array $moreReturnProperties
140 * Additional return fields.
141 * @param int $exportMode
143 * @param string $componentClause
145 * @param string $componentTable
147 * @param bool $mergeSameAddress
148 * Merge records if they have same address.
149 * @param bool $mergeSameHousehold
150 * Merge records if they belong to the same household.
152 * @param array $exportParams
153 * @param string $queryOperator
156 * An array can be requested from within a unit test.
158 * @throws \CRM_Core_Exception
160 public static function exportComponents(
166 $moreReturnProperties = NULL,
167 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
168 $componentClause = NULL,
169 $componentTable = NULL,
170 $mergeSameAddress = FALSE,
171 $mergeSameHousehold = FALSE,
173 $queryOperator = 'AND'
177 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
178 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
181 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
182 // If an Additional Group is selected, then all contacts in that group are
183 // added to the export set (filtering out duplicates).
184 // Really - the calling function could do this ... just saying
185 // @todo take a whip to the calling function.
186 CRM_Core_DAO
::executeQuery("
187 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"
190 // rectify params to what proximity search expects if there is a value for prox_distance
192 // @todo - move this back to the calling functions
193 if (!empty($params)) {
194 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
196 // @todo everything from this line up should go back to the calling functions.
197 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress);
198 if ($moreReturnProperties) {
199 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
202 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order);
204 // This perhaps only needs calling when $mergeSameHousehold == 1
205 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
207 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
208 if (!$selectAll && $componentTable) {
209 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
211 elseif ($componentClause) {
212 $whereClauses[] = $componentClause;
215 // CRM-13982 - check if is deleted
216 foreach ($params as $value) {
217 if ($value[0] == 'contact_is_deleted') {
218 unset($whereClauses['trash_clause']);
223 $where = "WHERE " . implode(' AND ', $whereClauses);
226 $where .= " AND " . implode(' AND ', $whereClauses);
229 $queryString = "$select $from $where $having";
231 $groupBy = self
::getGroupBy($processor, $query);
233 $queryString .= $groupBy;
236 // always add contact_a.id to the ORDER clause
237 // so the order is deterministic
239 if (strpos('contact_a.id', $order) === FALSE) {
240 $order .= ", contact_a.id";
243 list($field, $dir) = explode(' ', $order, 2);
244 $field = trim($field);
245 if (!empty($processor->getReturnProperties()[$field])) {
247 $queryString .= " ORDER BY $order";
251 $addPaymentHeader = FALSE;
253 list($outputColumns, $metadata) = self
::getExportStructureArrays($processor);
255 if ($processor->isMergeSameAddress()) {
256 //make sure the addressee fields are selected
257 //while using merge same address feature
258 // some columns are required for assistance incase they are not already present
259 $exportParams['merge_same_address']['temp_columns'] = $processor->getAdditionalFieldsForSameAddressMerge();
260 // This is silly - we should do this at the point when the array is used...
261 if (isset($exportParams['merge_same_address']['temp_columns']['id'])) {
262 unset($exportParams['merge_same_address']['temp_columns']['id']);
263 $exportParams['merge_same_address']['temp_columns']['civicrm_primary_id'] = 1;
265 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
266 // test exists covering this...
267 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
268 $processor->setColumnAsCalculationOnly($field);
272 $paymentDetails = [];
273 if ($processor->isExportPaymentFields()) {
274 // get payment related in for event and members
275 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
276 //get all payment headers.
277 // If we haven't selected specific payment fields, load in all the
279 if (!$processor->isExportSpecifiedPaymentFields()) {
280 if (!empty($paymentDetails)) {
281 $addPaymentHeader = TRUE;
282 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
283 $processor->addOutputSpecification($paymentField);
289 $componentDetails = [];
291 $rowCount = self
::EXPORT_ROW_COUNT
;
293 // we write to temp table often to avoid using too much memory
298 $headerRows = $processor->getHeaderRows();
299 $sqlColumns = $processor->getSQLColumns();
300 $processor->setTemporaryTable(self
::createTempTable($sqlColumns));
301 $limitReached = FALSE;
303 while (!$limitReached) {
304 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
305 CRM_Core_DAO
::disableFullGroupByMode();
306 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
307 CRM_Core_DAO
::reenableFullGroupByMode();
308 // If this is less than our limit by the end of the iteration we do not need to run the query again to
309 // check if some remain.
310 $rowsThisIteration = 0;
312 while ($iterationDAO->fetch()) {
314 $rowsThisIteration++
;
315 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $processor);
316 if ($row === FALSE) {
320 // add component info
321 // write the row to a file
322 $componentDetails[] = $row;
324 // output every $tempRowCount rows
325 if ($count %
$tempRowCount == 0) {
326 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
327 $componentDetails = [];
330 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
331 $limitReached = TRUE;
333 $offset +
= $rowCount;
336 if ($processor->getTemporaryTable()) {
337 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
339 // do merge same address and merge same household processing
340 if ($mergeSameAddress) {
341 self
::mergeSameAddress($processor, $sqlColumns, $exportParams);
345 $table = $processor->getTemporaryTable();
346 CRM_Utils_Hook
::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
347 if ($table !== $processor->getTemporaryTable()) {
348 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
349 $processor->setTemporaryTable($table);
352 // In order to be able to write a unit test against this function we need to suppress
353 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
354 if (empty($exportParams['suppress_csv_for_testing'])) {
355 self
::writeCSVFromTable($headerRows, $sqlColumns, $processor);
358 // return tableName sqlColumns headerRows in test context
359 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
362 // delete the export temp table and component table
363 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
364 CRM_Core_DAO
::executeQuery($sql);
365 CRM_Core_DAO
::reenableFullGroupByMode();
366 CRM_Utils_System
::civiExit(0, ['processor' => $processor]);
369 CRM_Core_DAO
::reenableFullGroupByMode();
370 throw new CRM_Core_Exception(ts('No records to export'));
375 * Handle import error file creation.
377 public static function invoke() {
378 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
379 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
380 if (empty($parserName) ||
empty($type)) {
384 // clean and ensure parserName is a valid string
385 $parserName = CRM_Utils_String
::munge($parserName);
386 $parserClass = explode('_', $parserName);
388 // make sure parserClass is in the CRM namespace and
389 // at least 3 levels deep
390 if ($parserClass[0] == 'CRM' &&
391 count($parserClass) >= 3
393 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
394 // ensure the functions exists
395 if (method_exists($parserName, 'errorFileName') &&
396 method_exists($parserName, 'saveFileName')
398 $errorFileName = $parserName::errorFileName($type);
399 $saveFileName = $parserName::saveFileName($type);
400 if (!empty($errorFileName) && !empty($saveFileName)) {
401 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
402 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
403 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
404 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
405 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
407 readfile($errorFileName);
411 CRM_Utils_System
::civiExit();
415 * @param $customSearchClass
419 public static function exportCustom($customSearchClass, $formValues, $order) {
420 $ext = CRM_Extension_System
::singleton()->getMapper();
421 if (!$ext->isExtensionClass($customSearchClass)) {
422 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
425 require_once $ext->classToPath($customSearchClass);
427 $search = new $customSearchClass($formValues);
429 $includeContactIDs = FALSE;
430 if ($formValues['radio_ts'] == 'ts_sel') {
431 $includeContactIDs = TRUE;
434 $sql = $search->all(0, 0, $order, $includeContactIDs);
436 $columns = $search->columns();
438 $header = array_keys($columns);
439 $fields = array_values($columns);
442 $dao = CRM_Core_DAO
::executeQuery($sql);
444 if (method_exists($search, 'alterRow')) {
447 while ($dao->fetch()) {
450 foreach ($fields as $field) {
451 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
452 $row[$field] = $dao->$unqualified_field;
455 $search->alterRow($row);
460 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
461 CRM_Utils_System
::civiExit();
465 * @param \CRM_Export_BAO_ExportProcessor $processor
469 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
470 $tableName = $processor->getTemporaryTable();
471 if (empty($details)) {
480 $id = CRM_Core_DAO
::singleValueQuery($sql);
487 foreach ($details as $row) {
489 $valueString = [$id];
490 foreach ($row as $value) {
492 $valueString[] = "''";
495 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
498 $sqlClause[] = '(' . implode(',', $valueString) . ')';
500 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
501 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
503 $sqlValueString = implode(",\n", $sqlClause);
506 INSERT INTO $tableName $sqlColumnString
507 VALUES $sqlValueString
509 CRM_Core_DAO
::executeQuery($sql);
517 public static function createTempTable($sqlColumns) {
518 //creating a temporary table for the search result that need be exported
519 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
521 // also create the sql table
522 $exportTempTable->drop();
524 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
525 if (!empty($sqlColumns)) {
526 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
529 $sql .= "\n PRIMARY KEY ( id )";
531 // add indexes for street_address and household_name if present
535 'civicrm_primary_id',
538 foreach ($addIndices as $index) {
539 if (isset($sqlColumns[$index])) {
541 INDEX index_{$index}( $index )
546 $exportTempTable->createWithColumns($sql);
547 return $exportTempTable->getName();
551 * @param \CRM_Export_BAO_ExportProcessor $processor
553 * @param array $exportParams
555 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
556 $greetingOptions = CRM_Export_Form_Select
::getGreetingOptions();
558 if (!empty($greetingOptions)) {
559 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
560 foreach ($greetingOptions as $key => $value) {
561 if ($option = CRM_Utils_Array
::value($key, $exportParams)) {
562 if ($greetingOptions[$key][$option] == ts('Other')) {
563 $exportParams[$key] = $exportParams["{$key}_other"];
565 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
566 $exportParams[$key] = '';
569 $exportParams[$key] = $greetingOptions[$key][$option];
574 $tableName = $processor->getTemporaryTable();
575 // check if any records are present based on if they have used shared address feature,
576 // and not based on if city / state .. matches.
578 SELECT r1.id as copy_id,
579 r1.civicrm_primary_id as copy_contact_id,
580 r1.addressee as copy_addressee,
581 r1.addressee_id as copy_addressee_id,
582 r1.postal_greeting as copy_postal_greeting,
583 r1.postal_greeting_id as copy_postal_greeting_id,
585 r2.civicrm_primary_id as master_contact_id,
586 r2.postal_greeting as master_postal_greeting,
587 r2.postal_greeting_id as master_postal_greeting_id,
588 r2.addressee as master_addressee,
589 r2.addressee_id as master_addressee_id
591 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
592 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
594 $linkedMerge = $processor->buildMasterCopyArray($sql, $exportParams, TRUE);
596 // find all the records that have the same street address BUT not in a household
597 // require match on city and state as well
599 SELECT r1.id as master_id,
600 r1.civicrm_primary_id as master_contact_id,
601 r1.postal_greeting as master_postal_greeting,
602 r1.postal_greeting_id as master_postal_greeting_id,
603 r1.addressee as master_addressee,
604 r1.addressee_id as master_addressee_id,
606 r2.civicrm_primary_id as copy_contact_id,
607 r2.postal_greeting as copy_postal_greeting,
608 r2.postal_greeting_id as copy_postal_greeting_id,
609 r2.addressee as copy_addressee,
610 r2.addressee_id as copy_addressee_id
612 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
613 r1.city = r2.city AND
614 r1.state_province_id = r2.state_province_id )
615 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
616 AND ( r2.household_name IS NULL OR r2.household_name = '' )
617 AND ( r1.street_address != '' )
621 $merge = $processor->buildMasterCopyArray($sql, $exportParams);
623 // unset ids from $merge already present in $linkedMerge
624 foreach ($linkedMerge as $masterID => $values) {
626 $keys = array_merge($keys, array_keys($values['copy']));
627 foreach ($merge as $mid => $vals) {
628 if (in_array($mid, $keys)) {
632 foreach ($values['copy'] as $copyId) {
633 if (in_array($copyId, $keys)) {
634 unset($merge[$mid]['copy'][$copyId]);
640 $merge = $merge +
$linkedMerge;
642 foreach ($merge as $masterID => $values) {
645 SET addressee = %1, postal_greeting = %2, email_greeting = %3
649 1 => [$values['addressee'], 'String'],
650 2 => [$values['postalGreeting'], 'String'],
651 3 => [$values['emailGreeting'], 'String'],
652 4 => [$masterID, 'Integer'],
654 CRM_Core_DAO
::executeQuery($sql, $params);
657 $deleteIDs = array_keys($values['copy']);
658 $deleteIDString = implode(',', $deleteIDs);
660 DELETE FROM $tableName
661 WHERE id IN ( $deleteIDString )
663 CRM_Core_DAO
::executeQuery($sql);
666 // unset temporary columns that were added for postal mailing format
667 // @todo - this part is pretty close to ready to be removed....
668 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
669 $unsetKeys = array_keys($sqlColumns);
670 foreach ($unsetKeys as $headerKey => $sqlColKey) {
671 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
672 unset($sqlColumns[$sqlColKey]);
681 * @param \CRM_Export_BAO_ExportProcessor $processor
683 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
684 $exportTempTable = $processor->getTemporaryTable();
685 $exportMode = $processor->getExportMode();
688 $limit = self
::EXPORT_ROW_COUNT
;
690 $query = "SELECT * FROM $exportTempTable";
693 $limitQuery = $query . "
694 LIMIT $offset, $limit
696 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
702 $componentDetails = [];
703 while ($dao->fetch()) {
706 foreach ($sqlColumns as $column => $dontCare) {
707 $row[$column] = $dao->$column;
709 $componentDetails[] = $row;
711 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
718 $writeHeader = FALSE;
724 * Build componentPayment fields.
726 * This is no longer used by export but BAO_Mapping still calls it & we
727 * should find a generic way to handle this or move this to that class.
731 public static function componentPaymentFields() {
732 static $componentPaymentFields;
733 if (!isset($componentPaymentFields)) {
734 $componentPaymentFields = [
735 'componentPaymentField_total_amount' => ts('Total Amount'),
736 'componentPaymentField_contribution_status' => ts('Contribution Status'),
737 'componentPaymentField_received_date' => ts('Date Received'),
738 'componentPaymentField_payment_instrument' => ts('Payment Method'),
739 'componentPaymentField_transaction_id' => ts('Transaction ID'),
742 return $componentPaymentFields;
746 * Get the various arrays that we use to structure our output.
748 * The extraction of these has been moved to a separate function for clarity and so that
749 * tests can be added - in particular on the $outputHeaders array.
751 * However it still feels a bit like something that I'm too polite to write down and this should be seen
752 * as a step on the refactoring path rather than how it should be.
754 * @param \CRM_Export_BAO_ExportProcessor $processor
757 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
758 * alias for the field generated by BAO_Query object.
759 * - headerRows Array of the column header strings to put in the csv header - non-associative.
760 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
761 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
762 * I'm too embarassed to discuss here.
764 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
765 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
766 * in the main DAO loop is done once per row & that coule be 100,000 times.)
767 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
768 * - a) the function used is more efficient or
769 * - b) this code is old & outdated. Submit your answers to circular bin or better
770 * yet find a way to comment them for posterity.
772 public static function getExportStructureArrays($processor) {
773 $outputColumns = $metadata = [];
774 $queryFields = $processor->getQueryFields();
775 foreach ($processor->getReturnProperties() as $key => $value) {
776 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
777 $outputColumns[$key] = $value;
778 $processor->addOutputSpecification($key);
780 elseif ($processor->isRelationshipTypeKey($key)) {
781 $outputColumns[$key] = $value;
782 foreach ($value as $relationField => $relationValue) {
783 // below block is same as primary block (duplicate)
784 if (isset($queryFields[$relationField]['title'])) {
785 $processor->addOutputSpecification($relationField, $key);
787 elseif (is_array($relationValue) && $relationField == 'location') {
788 // fix header for location type case
789 foreach ($relationValue as $ltype => $val) {
790 foreach (array_keys($val) as $fld) {
791 $type = explode('-', $fld);
792 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
799 foreach ($value as $locationType => $locationFields) {
800 foreach (array_keys($locationFields) as $locationFieldName) {
801 $type = explode('-', $locationFieldName);
803 $actualDBFieldName = $type[0];
804 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
806 if (!empty($type[1])) {
807 $daoFieldName .= "-" . $type[1];
809 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
810 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
811 $outputColumns[$daoFieldName] = TRUE;
816 return [$outputColumns, $metadata];
820 * Get the values of linked household contact.
822 * @param CRM_Core_DAO $relDAO
823 * @param array $value
824 * @param string $field
827 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
828 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
829 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
830 $i18n = CRM_Core_I18n
::singleton();
831 $field = $field . '_';
833 foreach ($value as $relationField => $relationValue) {
834 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
835 $fieldValue = $relDAO->$relationField;
836 if ($relationField == 'phone_type_id') {
837 $fieldValue = $phoneTypes[$relationValue];
839 elseif ($relationField == 'provider_id') {
840 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
843 elseif (is_object($relDAO) && in_array($relationField, [
848 //special case for greeting replacement
849 $fldValue = "{$relationField}_display";
850 $fieldValue = $relDAO->$fldValue;
853 elseif (is_object($relDAO) && $relationField == 'state_province') {
854 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
856 elseif (is_object($relDAO) && $relationField == 'country') {
857 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
862 $relPrefix = $field . $relationField;
864 if (is_object($relDAO) && $relationField == 'id') {
865 $row[$relPrefix] = $relDAO->contact_id
;
867 elseif (is_array($relationValue) && $relationField == 'location') {
868 foreach ($relationValue as $ltype => $val) {
869 // If the location name has a space in it the we need to handle that. This
870 // is kinda hacky but specifically covered in the ExportTest so later efforts to
871 // improve it should be secure in the knowled it will be caught.
872 $ltype = str_replace(' ', '_', $ltype);
873 foreach (array_keys($val) as $fld) {
874 $type = explode('-', $fld);
875 $fldValue = "{$ltype}-" . $type[0];
876 if (!empty($type[1])) {
877 $fldValue .= "-" . $type[1];
879 // CRM-3157: localise country, region (both have ‘country’ context)
880 // and state_province (‘province’ context)
882 case (!is_object($relDAO)):
883 $row[$field . '_' . $fldValue] = '';
886 case in_array('country', $type):
887 case in_array('world_region', $type):
888 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
889 ['context' => 'country']
893 case in_array('state_province', $type):
894 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
895 ['context' => 'province']
900 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
906 elseif (isset($fieldValue) && $fieldValue != '') {
907 //check for custom data
908 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
909 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
912 //normal relationship fields
913 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
914 switch ($relationField) {
917 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
920 case 'state_province':
921 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
925 $row[$relPrefix] = $fieldValue;
931 // if relation field is empty or null
932 $row[$relPrefix] = '';
938 * Get the ids that we want to get related contact details for.
941 * @param int $exportMode
945 protected static function getIDsForRelatedContact($ids, $exportMode) {
946 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
949 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
951 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
952 $dao = CRM_Core_DAO
::executeQuery("
953 SELECT contact_id FROM civicrm_activity_contact
954 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
955 record_type_id = {$sourceID}
958 while ($dao->fetch()) {
959 $relIDs[] = $dao->contact_id
;
963 $component = self
::exportComponent($exportMode);
965 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
966 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
969 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
976 * @param \CRM_Export_BAO_ExportProcessor $processor
977 * @param $componentTable
979 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
980 $allRelContactArray = $relationQuery = [];
981 $queryMode = $processor->getQueryMode();
982 $exportMode = $processor->getExportMode();
984 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
985 $allRelContactArray[$relationshipKey] = [];
986 // build Query for each relationship
987 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
988 NULL, FALSE, FALSE, $queryMode
990 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
992 list($id, $direction) = explode('_', $relationshipKey, 2);
993 // identify the relationship direction
994 $contactA = 'contact_id_a';
995 $contactB = 'contact_id_b';
996 if ($direction == 'b_a') {
997 $contactA = 'contact_id_b';
998 $contactB = 'contact_id_a';
1000 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1002 $relationshipJoin = $relationshipClause = '';
1003 if (!$selectAll && $componentTable) {
1004 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1006 elseif (!empty($relIDs)) {
1007 $relID = implode(',', $relIDs);
1008 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1011 $relationFrom = " {$relationFrom}
1012 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1013 {$relationshipJoin} ";
1015 //check for active relationship status only
1016 $today = date('Ymd');
1017 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1018 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1019 CRM_Core_DAO
::disableFullGroupByMode();
1020 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1021 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1023 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1024 CRM_Core_DAO
::reenableFullGroupByMode();
1026 while ($allRelContactDAO->fetch()) {
1027 $relationQuery->convertToPseudoNames($allRelContactDAO);
1029 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1030 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1031 foreach (array_keys($relationReturnProperties) as $property) {
1032 if ($property === 'location') {
1033 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1034 // $processor->setRelationshipValue from fetchRelationshipDetails
1035 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1036 foreach (array_keys($locationValues) as $locationValue) {
1037 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1038 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1043 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);