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);
201 $paymentTableId = $processor->getPaymentTableID();
203 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order);
205 // This perhaps only needs calling when $mergeSameHousehold == 1
206 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
208 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
209 if (!$selectAll && $componentTable) {
210 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
212 elseif ($componentClause) {
213 $whereClauses[] = $componentClause;
216 // CRM-13982 - check if is deleted
217 foreach ($params as $value) {
218 if ($value[0] == 'contact_is_deleted') {
219 unset($whereClauses['trash_clause']);
224 $where = "WHERE " . implode(' AND ', $whereClauses);
227 $where .= " AND " . implode(' AND ', $whereClauses);
230 $queryString = "$select $from $where $having";
232 $groupBy = self
::getGroupBy($processor, $query);
234 $queryString .= $groupBy;
237 // always add contact_a.id to the ORDER clause
238 // so the order is deterministic
240 if (strpos('contact_a.id', $order) === FALSE) {
241 $order .= ", contact_a.id";
244 list($field, $dir) = explode(' ', $order, 2);
245 $field = trim($field);
246 if (!empty($processor->getReturnProperties()[$field])) {
248 $queryString .= " ORDER BY $order";
252 $addPaymentHeader = FALSE;
254 list($outputColumns, $metadata) = self
::getExportStructureArrays($processor);
256 if ($processor->isMergeSameAddress()) {
257 //make sure the addressee fields are selected
258 //while using merge same address feature
259 // some columns are required for assistance incase they are not already present
260 $exportParams['merge_same_address']['temp_columns'] = $processor->getAdditionalFieldsForSameAddressMerge();
261 // This is silly - we should do this at the point when the array is used...
262 if (isset($exportParams['merge_same_address']['temp_columns']['id'])) {
263 unset($exportParams['merge_same_address']['temp_columns']['id']);
264 $exportParams['merge_same_address']['temp_columns']['civicrm_primary_id'] = 1;
266 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
267 // test exists covering this...
268 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
269 $processor->setColumnAsCalculationOnly($field);
273 $paymentDetails = [];
274 if ($processor->isExportPaymentFields()) {
275 // get payment related in for event and members
276 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
277 //get all payment headers.
278 // If we haven't selected specific payment fields, load in all the
280 if (!$processor->isExportSpecifiedPaymentFields()) {
281 if (!empty($paymentDetails)) {
282 $addPaymentHeader = TRUE;
283 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
284 $processor->addOutputSpecification($paymentField);
290 $componentDetails = [];
292 $rowCount = self
::EXPORT_ROW_COUNT
;
294 // we write to temp table often to avoid using too much memory
299 $headerRows = $processor->getHeaderRows();
300 $sqlColumns = $processor->getSQLColumns();
301 $processor->setTemporaryTable(self
::createTempTable($sqlColumns));
302 $limitReached = FALSE;
304 while (!$limitReached) {
305 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
306 CRM_Core_DAO
::disableFullGroupByMode();
307 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
308 CRM_Core_DAO
::reenableFullGroupByMode();
309 // If this is less than our limit by the end of the iteration we do not need to run the query again to
310 // check if some remain.
311 $rowsThisIteration = 0;
313 while ($iterationDAO->fetch()) {
315 $rowsThisIteration++
;
316 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
317 if ($row === FALSE) {
321 // add component info
322 // write the row to a file
323 $componentDetails[] = $row;
325 // output every $tempRowCount rows
326 if ($count %
$tempRowCount == 0) {
327 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
328 $componentDetails = [];
331 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
332 $limitReached = TRUE;
334 $offset +
= $rowCount;
337 if ($processor->getTemporaryTable()) {
338 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
340 // do merge same address and merge same household processing
341 if ($mergeSameAddress) {
342 self
::mergeSameAddress($processor, $sqlColumns, $exportParams);
346 $table = $processor->getTemporaryTable();
347 CRM_Utils_Hook
::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
348 if ($table !== $processor->getTemporaryTable()) {
349 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
350 $processor->setTemporaryTable($table);
353 // In order to be able to write a unit test against this function we need to suppress
354 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
355 if (empty($exportParams['suppress_csv_for_testing'])) {
356 self
::writeCSVFromTable($headerRows, $sqlColumns, $processor);
359 // return tableName sqlColumns headerRows in test context
360 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
363 // delete the export temp table and component table
364 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
365 CRM_Core_DAO
::executeQuery($sql);
366 CRM_Core_DAO
::reenableFullGroupByMode();
367 CRM_Utils_System
::civiExit(0, ['processor' => $processor]);
370 CRM_Core_DAO
::reenableFullGroupByMode();
371 throw new CRM_Core_Exception(ts('No records to export'));
376 * Handle import error file creation.
378 public static function invoke() {
379 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
380 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
381 if (empty($parserName) ||
empty($type)) {
385 // clean and ensure parserName is a valid string
386 $parserName = CRM_Utils_String
::munge($parserName);
387 $parserClass = explode('_', $parserName);
389 // make sure parserClass is in the CRM namespace and
390 // at least 3 levels deep
391 if ($parserClass[0] == 'CRM' &&
392 count($parserClass) >= 3
394 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
395 // ensure the functions exists
396 if (method_exists($parserName, 'errorFileName') &&
397 method_exists($parserName, 'saveFileName')
399 $errorFileName = $parserName::errorFileName($type);
400 $saveFileName = $parserName::saveFileName($type);
401 if (!empty($errorFileName) && !empty($saveFileName)) {
402 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
403 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
404 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
405 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
406 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
408 readfile($errorFileName);
412 CRM_Utils_System
::civiExit();
416 * @param $customSearchClass
420 public static function exportCustom($customSearchClass, $formValues, $order) {
421 $ext = CRM_Extension_System
::singleton()->getMapper();
422 if (!$ext->isExtensionClass($customSearchClass)) {
423 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
426 require_once $ext->classToPath($customSearchClass);
428 $search = new $customSearchClass($formValues);
430 $includeContactIDs = FALSE;
431 if ($formValues['radio_ts'] == 'ts_sel') {
432 $includeContactIDs = TRUE;
435 $sql = $search->all(0, 0, $order, $includeContactIDs);
437 $columns = $search->columns();
439 $header = array_keys($columns);
440 $fields = array_values($columns);
443 $dao = CRM_Core_DAO
::executeQuery($sql);
445 if (method_exists($search, 'alterRow')) {
448 while ($dao->fetch()) {
451 foreach ($fields as $field) {
452 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
453 $row[$field] = $dao->$unqualified_field;
456 $search->alterRow($row);
461 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
462 CRM_Utils_System
::civiExit();
466 * @param \CRM_Export_BAO_ExportProcessor $processor
470 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
471 $tableName = $processor->getTemporaryTable();
472 if (empty($details)) {
481 $id = CRM_Core_DAO
::singleValueQuery($sql);
488 foreach ($details as $row) {
490 $valueString = [$id];
491 foreach ($row as $value) {
493 $valueString[] = "''";
496 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
499 $sqlClause[] = '(' . implode(',', $valueString) . ')';
501 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
502 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
504 $sqlValueString = implode(",\n", $sqlClause);
507 INSERT INTO $tableName $sqlColumnString
508 VALUES $sqlValueString
510 CRM_Core_DAO
::executeQuery($sql);
518 public static function createTempTable($sqlColumns) {
519 //creating a temporary table for the search result that need be exported
520 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
522 // also create the sql table
523 $exportTempTable->drop();
525 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
526 if (!empty($sqlColumns)) {
527 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
530 $sql .= "\n PRIMARY KEY ( id )";
532 // add indexes for street_address and household_name if present
536 'civicrm_primary_id',
539 foreach ($addIndices as $index) {
540 if (isset($sqlColumns[$index])) {
542 INDEX index_{$index}( $index )
547 $exportTempTable->createWithColumns($sql);
548 return $exportTempTable->getName();
552 * @param \CRM_Export_BAO_ExportProcessor $processor
554 * @param array $exportParams
556 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
557 $greetingOptions = CRM_Export_Form_Select
::getGreetingOptions();
559 if (!empty($greetingOptions)) {
560 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
561 foreach ($greetingOptions as $key => $value) {
562 if ($option = CRM_Utils_Array
::value($key, $exportParams)) {
563 if ($greetingOptions[$key][$option] == ts('Other')) {
564 $exportParams[$key] = $exportParams["{$key}_other"];
566 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
567 $exportParams[$key] = '';
570 $exportParams[$key] = $greetingOptions[$key][$option];
575 $tableName = $processor->getTemporaryTable();
576 // check if any records are present based on if they have used shared address feature,
577 // and not based on if city / state .. matches.
579 SELECT r1.id as copy_id,
580 r1.civicrm_primary_id as copy_contact_id,
581 r1.addressee as copy_addressee,
582 r1.addressee_id as copy_addressee_id,
583 r1.postal_greeting as copy_postal_greeting,
584 r1.postal_greeting_id as copy_postal_greeting_id,
586 r2.civicrm_primary_id as master_contact_id,
587 r2.postal_greeting as master_postal_greeting,
588 r2.postal_greeting_id as master_postal_greeting_id,
589 r2.addressee as master_addressee,
590 r2.addressee_id as master_addressee_id
592 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
593 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
595 $linkedMerge = $processor->buildMasterCopyArray($sql, $exportParams, TRUE);
597 // find all the records that have the same street address BUT not in a household
598 // require match on city and state as well
600 SELECT r1.id as master_id,
601 r1.civicrm_primary_id as master_contact_id,
602 r1.postal_greeting as master_postal_greeting,
603 r1.postal_greeting_id as master_postal_greeting_id,
604 r1.addressee as master_addressee,
605 r1.addressee_id as master_addressee_id,
607 r2.civicrm_primary_id as copy_contact_id,
608 r2.postal_greeting as copy_postal_greeting,
609 r2.postal_greeting_id as copy_postal_greeting_id,
610 r2.addressee as copy_addressee,
611 r2.addressee_id as copy_addressee_id
613 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
614 r1.city = r2.city AND
615 r1.state_province_id = r2.state_province_id )
616 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
617 AND ( r2.household_name IS NULL OR r2.household_name = '' )
618 AND ( r1.street_address != '' )
622 $merge = $processor->buildMasterCopyArray($sql, $exportParams);
624 // unset ids from $merge already present in $linkedMerge
625 foreach ($linkedMerge as $masterID => $values) {
627 $keys = array_merge($keys, array_keys($values['copy']));
628 foreach ($merge as $mid => $vals) {
629 if (in_array($mid, $keys)) {
633 foreach ($values['copy'] as $copyId) {
634 if (in_array($copyId, $keys)) {
635 unset($merge[$mid]['copy'][$copyId]);
641 $merge = $merge +
$linkedMerge;
643 foreach ($merge as $masterID => $values) {
646 SET addressee = %1, postal_greeting = %2, email_greeting = %3
650 1 => [$values['addressee'], 'String'],
651 2 => [$values['postalGreeting'], 'String'],
652 3 => [$values['emailGreeting'], 'String'],
653 4 => [$masterID, 'Integer'],
655 CRM_Core_DAO
::executeQuery($sql, $params);
658 $deleteIDs = array_keys($values['copy']);
659 $deleteIDString = implode(',', $deleteIDs);
661 DELETE FROM $tableName
662 WHERE id IN ( $deleteIDString )
664 CRM_Core_DAO
::executeQuery($sql);
667 // unset temporary columns that were added for postal mailing format
668 // @todo - this part is pretty close to ready to be removed....
669 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
670 $unsetKeys = array_keys($sqlColumns);
671 foreach ($unsetKeys as $headerKey => $sqlColKey) {
672 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
673 unset($sqlColumns[$sqlColKey]);
682 * @param \CRM_Export_BAO_ExportProcessor $processor
684 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
685 $exportTempTable = $processor->getTemporaryTable();
686 $exportMode = $processor->getExportMode();
689 $limit = self
::EXPORT_ROW_COUNT
;
691 $query = "SELECT * FROM $exportTempTable";
694 $limitQuery = $query . "
695 LIMIT $offset, $limit
697 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
703 $componentDetails = [];
704 while ($dao->fetch()) {
707 foreach ($sqlColumns as $column => $dontCare) {
708 $row[$column] = $dao->$column;
710 $componentDetails[] = $row;
712 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
719 $writeHeader = FALSE;
725 * Build componentPayment fields.
727 * This is no longer used by export but BAO_Mapping still calls it & we
728 * should find a generic way to handle this or move this to that class.
732 public static function componentPaymentFields() {
733 static $componentPaymentFields;
734 if (!isset($componentPaymentFields)) {
735 $componentPaymentFields = [
736 'componentPaymentField_total_amount' => ts('Total Amount'),
737 'componentPaymentField_contribution_status' => ts('Contribution Status'),
738 'componentPaymentField_received_date' => ts('Date Received'),
739 'componentPaymentField_payment_instrument' => ts('Payment Method'),
740 'componentPaymentField_transaction_id' => ts('Transaction ID'),
743 return $componentPaymentFields;
747 * Get the various arrays that we use to structure our output.
749 * The extraction of these has been moved to a separate function for clarity and so that
750 * tests can be added - in particular on the $outputHeaders array.
752 * However it still feels a bit like something that I'm too polite to write down and this should be seen
753 * as a step on the refactoring path rather than how it should be.
755 * @param \CRM_Export_BAO_ExportProcessor $processor
758 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
759 * alias for the field generated by BAO_Query object.
760 * - headerRows Array of the column header strings to put in the csv header - non-associative.
761 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
762 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
763 * I'm too embarassed to discuss here.
765 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
766 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
767 * in the main DAO loop is done once per row & that coule be 100,000 times.)
768 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
769 * - a) the function used is more efficient or
770 * - b) this code is old & outdated. Submit your answers to circular bin or better
771 * yet find a way to comment them for posterity.
773 public static function getExportStructureArrays($processor) {
774 $outputColumns = $metadata = [];
775 $queryFields = $processor->getQueryFields();
776 foreach ($processor->getReturnProperties() as $key => $value) {
777 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
778 $outputColumns[$key] = $value;
779 $processor->addOutputSpecification($key);
781 elseif ($processor->isRelationshipTypeKey($key)) {
782 $outputColumns[$key] = $value;
783 foreach ($value as $relationField => $relationValue) {
784 // below block is same as primary block (duplicate)
785 if (isset($queryFields[$relationField]['title'])) {
786 $processor->addOutputSpecification($relationField, $key);
788 elseif (is_array($relationValue) && $relationField == 'location') {
789 // fix header for location type case
790 foreach ($relationValue as $ltype => $val) {
791 foreach (array_keys($val) as $fld) {
792 $type = explode('-', $fld);
793 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
800 foreach ($value as $locationType => $locationFields) {
801 foreach (array_keys($locationFields) as $locationFieldName) {
802 $type = explode('-', $locationFieldName);
804 $actualDBFieldName = $type[0];
805 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
807 if (!empty($type[1])) {
808 $daoFieldName .= "-" . $type[1];
810 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
811 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
812 $outputColumns[$daoFieldName] = TRUE;
817 return [$outputColumns, $metadata];
821 * Get the values of linked household contact.
823 * @param CRM_Core_DAO $relDAO
824 * @param array $value
825 * @param string $field
828 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
829 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
830 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
831 $i18n = CRM_Core_I18n
::singleton();
832 $field = $field . '_';
834 foreach ($value as $relationField => $relationValue) {
835 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
836 $fieldValue = $relDAO->$relationField;
837 if ($relationField == 'phone_type_id') {
838 $fieldValue = $phoneTypes[$relationValue];
840 elseif ($relationField == 'provider_id') {
841 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
844 elseif (is_object($relDAO) && in_array($relationField, [
849 //special case for greeting replacement
850 $fldValue = "{$relationField}_display";
851 $fieldValue = $relDAO->$fldValue;
854 elseif (is_object($relDAO) && $relationField == 'state_province') {
855 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
857 elseif (is_object($relDAO) && $relationField == 'country') {
858 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
863 $relPrefix = $field . $relationField;
865 if (is_object($relDAO) && $relationField == 'id') {
866 $row[$relPrefix] = $relDAO->contact_id
;
868 elseif (is_array($relationValue) && $relationField == 'location') {
869 foreach ($relationValue as $ltype => $val) {
870 // If the location name has a space in it the we need to handle that. This
871 // is kinda hacky but specifically covered in the ExportTest so later efforts to
872 // improve it should be secure in the knowled it will be caught.
873 $ltype = str_replace(' ', '_', $ltype);
874 foreach (array_keys($val) as $fld) {
875 $type = explode('-', $fld);
876 $fldValue = "{$ltype}-" . $type[0];
877 if (!empty($type[1])) {
878 $fldValue .= "-" . $type[1];
880 // CRM-3157: localise country, region (both have ‘country’ context)
881 // and state_province (‘province’ context)
883 case (!is_object($relDAO)):
884 $row[$field . '_' . $fldValue] = '';
887 case in_array('country', $type):
888 case in_array('world_region', $type):
889 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
890 ['context' => 'country']
894 case in_array('state_province', $type):
895 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
896 ['context' => 'province']
901 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
907 elseif (isset($fieldValue) && $fieldValue != '') {
908 //check for custom data
909 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
910 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
913 //normal relationship fields
914 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
915 switch ($relationField) {
918 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
921 case 'state_province':
922 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
926 $row[$relPrefix] = $fieldValue;
932 // if relation field is empty or null
933 $row[$relPrefix] = '';
939 * Get the ids that we want to get related contact details for.
942 * @param int $exportMode
946 protected static function getIDsForRelatedContact($ids, $exportMode) {
947 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
950 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
952 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
953 $dao = CRM_Core_DAO
::executeQuery("
954 SELECT contact_id FROM civicrm_activity_contact
955 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
956 record_type_id = {$sourceID}
959 while ($dao->fetch()) {
960 $relIDs[] = $dao->contact_id
;
964 $component = self
::exportComponent($exportMode);
966 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
967 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
970 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
977 * @param \CRM_Export_BAO_ExportProcessor $processor
978 * @param $componentTable
980 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
981 $allRelContactArray = $relationQuery = [];
982 $queryMode = $processor->getQueryMode();
983 $exportMode = $processor->getExportMode();
985 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
986 $allRelContactArray[$relationshipKey] = [];
987 // build Query for each relationship
988 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
989 NULL, FALSE, FALSE, $queryMode
991 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
993 list($id, $direction) = explode('_', $relationshipKey, 2);
994 // identify the relationship direction
995 $contactA = 'contact_id_a';
996 $contactB = 'contact_id_b';
997 if ($direction == 'b_a') {
998 $contactA = 'contact_id_b';
999 $contactB = 'contact_id_a';
1001 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1003 $relationshipJoin = $relationshipClause = '';
1004 if (!$selectAll && $componentTable) {
1005 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1007 elseif (!empty($relIDs)) {
1008 $relID = implode(',', $relIDs);
1009 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1012 $relationFrom = " {$relationFrom}
1013 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1014 {$relationshipJoin} ";
1016 //check for active relationship status only
1017 $today = date('Ymd');
1018 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1019 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1020 CRM_Core_DAO
::disableFullGroupByMode();
1021 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1022 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1024 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1025 CRM_Core_DAO
::reenableFullGroupByMode();
1027 while ($allRelContactDAO->fetch()) {
1028 $relationQuery->convertToPseudoNames($allRelContactDAO);
1030 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1031 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1032 foreach (array_keys($relationReturnProperties) as $property) {
1033 if ($property === 'location') {
1034 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1035 // $processor->setRelationshipValue from fetchRelationshipDetails
1036 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1037 foreach (array_keys($locationValues) as $locationValue) {
1038 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1039 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1044 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);