3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 * Key representing the head of household in the relationship array.
47 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
51 protected static $relationshipTypes = [];
54 * Get default return property for export based on mode
56 * @param int $exportMode
59 * @return string $property
60 * Default Return property
62 public static function defaultReturnProperty($exportMode) {
63 // hack to add default return property based on export mode
65 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
66 $property = 'contribution_id';
68 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
69 $property = 'participant_id';
71 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
72 $property = 'membership_id';
74 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
75 $property = 'pledge_id';
77 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
78 $property = 'case_id';
80 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
81 $property = 'grant_id';
83 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
84 $property = 'activity_id';
90 * Get Export component
92 * @param int $exportMode
95 * @return string $component
96 * CiviCRM Export Component
98 public static function exportComponent($exportMode) {
99 switch ($exportMode) {
100 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
101 $component = 'civicrm_contribution';
104 case CRM_Export_Form_Select
::EVENT_EXPORT
:
105 $component = 'civicrm_participant';
108 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
109 $component = 'civicrm_membership';
112 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
113 $component = 'civicrm_pledge';
116 case CRM_Export_Form_Select
::GRANT_EXPORT
:
117 $component = 'civicrm_grant';
124 * Get Query Group By Clause
125 * @param \CRM_Export_BAO_ExportProcessor $processor
127 * @param array $returnProperties
129 * @param object $query
130 * CRM_Contact_BAO_Query
132 * @return string $groupBy
135 public static function getGroupBy($processor, $returnProperties, $query) {
137 $exportMode = $processor->getExportMode();
138 $queryMode = $processor->getQueryMode();
139 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
140 CRM_Utils_Array
::value('notes', $returnProperties) ||
142 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
144 $groupBy = "contact_a.id";
147 switch ($exportMode) {
148 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
149 $groupBy = 'civicrm_contribution.id';
150 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
151 // especial group by when soft credit columns are included
152 $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
156 case CRM_Export_Form_Select
::EVENT_EXPORT
:
157 $groupBy = 'civicrm_participant.id';
160 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
161 $groupBy = "civicrm_membership.id";
165 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
166 $groupBy = "civicrm_activity.id ";
169 return $groupBy ?
' GROUP BY ' . $groupBy : '';
173 * Get the list the export fields.
175 * @param int $selectAll
176 * User preference while export.
179 * @param array $params
180 * Associated array of fields.
181 * @param string $order
183 * @param array $fields
184 * Associated array of fields.
185 * @param array $moreReturnProperties
186 * Additional return fields.
187 * @param int $exportMode
189 * @param string $componentClause
191 * @param string $componentTable
193 * @param bool $mergeSameAddress
194 * Merge records if they have same address.
195 * @param bool $mergeSameHousehold
196 * Merge records if they belong to the same household.
198 * @param array $exportParams
199 * @param string $queryOperator
202 * An array can be requested from within a unit test.
204 * @throws \CRM_Core_Exception
206 public static function exportComponents(
212 $moreReturnProperties = NULL,
213 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
214 $componentClause = NULL,
215 $componentTable = NULL,
216 $mergeSameAddress = FALSE,
217 $mergeSameHousehold = FALSE,
218 $exportParams = array(),
219 $queryOperator = 'AND'
222 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold);
223 $returnProperties = array();
224 self
::$relationshipTypes = $processor->getRelationshipTypes();
227 foreach ($fields as $key => $value) {
228 $fieldName = CRM_Utils_Array
::value(1, $value);
233 if ($processor->isRelationshipTypeKey($fieldName) && (!empty($value[2]) ||
!empty($value[4]))) {
234 $returnProperties[$fieldName] = $processor->setRelationshipReturnProperties($value, $fieldName);
236 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
237 $locationName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $value[2]);
238 if ($fieldName == 'phone') {
239 $returnProperties['location'][$locationName]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
241 elseif ($fieldName == 'im') {
242 $returnProperties['location'][$locationName]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
245 $returnProperties['location'][$locationName][$fieldName] = 1;
249 //hack to fix component fields
250 //revert mix of event_id and title
251 if ($fieldName == 'event_id') {
252 $returnProperties['event_id'] = 1;
255 $returnProperties[$fieldName] = 1;
259 $defaultExportMode = self
::defaultReturnProperty($exportMode);
260 if ($defaultExportMode) {
261 $returnProperties[$defaultExportMode] = 1;
265 $returnProperties = $processor->getDefaultReturnProperties();
267 // @todo - we are working towards this being entirely a property of the processor
268 $processor->setReturnProperties($returnProperties);
269 $paymentTableId = $processor->getPaymentTableID();
271 if ($mergeSameAddress) {
272 //make sure the addressee fields are selected
273 //while using merge same address feature
274 $returnProperties['addressee'] = 1;
275 $returnProperties['postal_greeting'] = 1;
276 $returnProperties['email_greeting'] = 1;
277 $returnProperties['street_name'] = 1;
278 $returnProperties['household_name'] = 1;
279 $returnProperties['street_address'] = 1;
280 $returnProperties['city'] = 1;
281 $returnProperties['state_province'] = 1;
283 // some columns are required for assistance incase they are not already present
284 $exportParams['merge_same_address']['temp_columns'] = array();
285 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
286 foreach ($tempColumns as $column) {
287 if (!array_key_exists($column, $returnProperties)) {
288 $returnProperties[$column] = 1;
289 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
290 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
295 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
296 // If an Additional Group is selected, then all contacts in that group are
297 // added to the export set (filtering out duplicates).
299 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";
300 CRM_Core_DAO
::executeQuery($query);
303 if ($moreReturnProperties) {
305 if (!empty($moreReturnProperties['group'])) {
306 unset($moreReturnProperties['group']);
307 $moreReturnProperties['groups'] = 1;
309 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
312 $exportParams['postal_mailing_export']['temp_columns'] = array();
313 if ($exportParams['exportOption'] == 2 &&
314 isset($exportParams['postal_mailing_export']) &&
315 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
317 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
318 foreach ($postalColumns as $column) {
319 if (!array_key_exists($column, $returnProperties)) {
320 $returnProperties[$column] = 1;
321 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
326 // rectify params to what proximity search expects if there is a value for prox_distance
328 if (!empty($params)) {
329 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
332 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
334 if ($mergeSameHousehold == 1) {
335 if (empty($returnProperties['id'])) {
336 $returnProperties['id'] = 1;
339 foreach ($returnProperties as $key => $value) {
340 if (!$processor->isRelationshipTypeKey($key)) {
341 foreach ($processor->getHouseholdRelationshipTypes() as $householdRelationshipType) {
342 if (!in_array($key, ['location_type', 'im_provider'])) {
343 $returnProperties[$householdRelationshipType][$key] = $value;
346 // @todo - don't use returnProperties above.
347 $processor->setHouseholdMergeReturnProperties($returnProperties[$householdRelationshipType]);
352 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
354 // make sure the groups stuff is included only if specifically specified
355 // by the fields param (CRM-1969), else we limit the contacts outputted to only
356 // ones that are part of a group
357 if (!empty($returnProperties['groups'])) {
358 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
359 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
360 // total hack for export, CRM-3618
361 $from = str_replace($oldClause,
367 if (!$selectAll && $componentTable) {
368 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
370 elseif ($componentClause) {
372 $where = "WHERE $componentClause";
375 $where .= " AND $componentClause";
379 // CRM-13982 - check if is deleted
380 $excludeTrashed = TRUE;
381 foreach ($params as $value) {
382 if ($value[0] == 'contact_is_deleted') {
383 $excludeTrashed = FALSE;
386 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
389 $where = "WHERE $trashClause";
392 $where .= " AND $trashClause";
395 $queryString = "$select $from $where $having";
397 $groupBy = self
::getGroupBy($processor, $returnProperties, $query);
399 $queryString .= $groupBy;
402 // always add contact_a.id to the ORDER clause
403 // so the order is deterministic
405 if (strpos('contact_a.id', $order) === FALSE) {
406 $order .= ", contact_a.id";
409 list($field, $dir) = explode(' ', $order, 2);
410 $field = trim($field);
411 if (!empty($returnProperties[$field])) {
413 $queryString .= " ORDER BY $order";
417 $addPaymentHeader = FALSE;
419 $paymentDetails = array();
420 if ($processor->isExportPaymentFields()) {
421 // get payment related in for event and members
422 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
423 //get all payment headers.
424 // If we haven't selected specific payment fields, load in all the
426 if (!$processor->isExportSpecifiedPaymentFields()) {
427 if (!empty($paymentDetails)) {
428 $addPaymentHeader = TRUE;
433 $componentDetails = array();
435 $rowCount = self
::EXPORT_ROW_COUNT
;
437 // we write to temp table often to avoid using too much memory
442 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
444 // add payment headers if required
445 if ($addPaymentHeader && $processor->isExportPaymentFields()) {
446 // @todo rather than do this for every single row do it before the loop starts.
447 // where other header definitions take place.
448 $headerRows = array_merge($headerRows, $processor->getPaymentHeaders());
449 foreach (array_keys($processor->getPaymentHeaders()) as $paymentHdr) {
450 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
454 $exportTempTable = self
::createTempTable($sqlColumns);
455 $limitReached = FALSE;
457 while (!$limitReached) {
458 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
459 CRM_Core_DAO
::disableFullGroupByMode();
460 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
461 CRM_Core_DAO
::reenableFullGroupByMode();
462 // If this is less than our limit by the end of the iteration we do not need to run the query again to
463 // check if some remain.
464 $rowsThisIteration = 0;
466 while ($iterationDAO->fetch()) {
468 $rowsThisIteration++
;
469 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
471 // add component info
472 // write the row to a file
473 $componentDetails[] = $row;
475 // output every $tempRowCount rows
476 if ($count %
$tempRowCount == 0) {
477 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
478 $componentDetails = array();
481 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
482 $limitReached = TRUE;
484 $offset +
= $rowCount;
487 if ($exportTempTable) {
488 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
490 // if postalMailing option is checked, exclude contacts who are deceased, have
491 // "Do not mail" privacy setting, or have no street address
492 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
493 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
495 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
498 // do merge same address and merge same household processing
499 if ($mergeSameAddress) {
500 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
503 // merge the records if they have corresponding households
504 if ($mergeSameHousehold) {
505 foreach ($processor->getHouseholdRelationshipTypes() as $householdRelationshipType) {
506 self
::mergeSameHousehold($exportTempTable, $sqlColumns, $householdRelationshipType);
511 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
513 // In order to be able to write a unit test against this function we need to suppress
514 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
515 if (empty($exportParams['suppress_csv_for_testing'])) {
516 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor);
519 // return tableName sqlColumns headerRows in test context
520 return array($exportTempTable, $sqlColumns, $headerRows);
523 // delete the export temp table and component table
524 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
525 CRM_Core_DAO
::executeQuery($sql);
526 CRM_Core_DAO
::reenableFullGroupByMode();
527 CRM_Utils_System
::civiExit();
530 CRM_Core_DAO
::reenableFullGroupByMode();
531 throw new CRM_Core_Exception(ts('No records to export'));
536 * Handle import error file creation.
538 public static function invoke() {
539 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
540 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
541 if (empty($parserName) ||
empty($type)) {
545 // clean and ensure parserName is a valid string
546 $parserName = CRM_Utils_String
::munge($parserName);
547 $parserClass = explode('_', $parserName);
549 // make sure parserClass is in the CRM namespace and
550 // at least 3 levels deep
551 if ($parserClass[0] == 'CRM' &&
552 count($parserClass) >= 3
554 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
555 // ensure the functions exists
556 if (method_exists($parserName, 'errorFileName') &&
557 method_exists($parserName, 'saveFileName')
559 $errorFileName = $parserName::errorFileName($type);
560 $saveFileName = $parserName::saveFileName($type);
561 if (!empty($errorFileName) && !empty($saveFileName)) {
562 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
563 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
564 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
565 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
566 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
568 readfile($errorFileName);
572 CRM_Utils_System
::civiExit();
576 * @param $customSearchClass
580 public static function exportCustom($customSearchClass, $formValues, $order) {
581 $ext = CRM_Extension_System
::singleton()->getMapper();
582 if (!$ext->isExtensionClass($customSearchClass)) {
583 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
586 require_once $ext->classToPath($customSearchClass);
588 $search = new $customSearchClass($formValues);
590 $includeContactIDs = FALSE;
591 if ($formValues['radio_ts'] == 'ts_sel') {
592 $includeContactIDs = TRUE;
595 $sql = $search->all(0, 0, $order, $includeContactIDs);
597 $columns = $search->columns();
599 $header = array_keys($columns);
600 $fields = array_values($columns);
603 $dao = CRM_Core_DAO
::executeQuery($sql);
605 if (method_exists($search, 'alterRow')) {
608 while ($dao->fetch()) {
611 foreach ($fields as $field) {
612 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
613 $row[$field] = $dao->$unqualified_field;
616 $search->alterRow($row);
621 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
622 CRM_Utils_System
::civiExit();
626 * @param \CRM_Export_BAO_ExportProcessor $processor
630 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
631 $sqlColumns[$processor->getMungedFieldName($field)] = $processor->getSqlColumnDefinition($field);
635 * @param string $tableName
639 public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
640 if (empty($details)) {
649 $id = CRM_Core_DAO
::singleValueQuery($sql);
654 $sqlClause = array();
656 foreach ($details as $row) {
658 $valueString = array($id);
659 foreach ($row as $value) {
661 $valueString[] = "''";
664 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
667 $sqlClause[] = '(' . implode(',', $valueString) . ')';
670 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
672 $sqlValueString = implode(",\n", $sqlClause);
675 INSERT INTO $tableName $sqlColumnString
676 VALUES $sqlValueString
678 CRM_Core_DAO
::executeQuery($sql);
686 public static function createTempTable($sqlColumns) {
687 //creating a temporary table for the search result that need be exported
688 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
690 // also create the sql table
691 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
692 CRM_Core_DAO
::executeQuery($sql);
695 CREATE TABLE {$exportTempTable} (
696 id int unsigned NOT NULL AUTO_INCREMENT,
698 $sql .= implode(",\n", array_values($sqlColumns));
703 // add indexes for street_address and household_name if present
707 'civicrm_primary_id',
710 foreach ($addIndices as $index) {
711 if (isset($sqlColumns[$index])) {
713 INDEX index_{$index}( $index )
719 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
722 CRM_Core_DAO
::executeQuery($sql);
723 return $exportTempTable;
727 * @param string $tableName
730 * @param array $exportParams
732 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
733 // check if any records are present based on if they have used shared address feature,
734 // and not based on if city / state .. matches.
736 SELECT r1.id as copy_id,
737 r1.civicrm_primary_id as copy_contact_id,
738 r1.addressee as copy_addressee,
739 r1.addressee_id as copy_addressee_id,
740 r1.postal_greeting as copy_postal_greeting,
741 r1.postal_greeting_id as copy_postal_greeting_id,
743 r2.civicrm_primary_id as master_contact_id,
744 r2.postal_greeting as master_postal_greeting,
745 r2.postal_greeting_id as master_postal_greeting_id,
746 r2.addressee as master_addressee,
747 r2.addressee_id as master_addressee_id
749 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
750 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
752 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
754 // find all the records that have the same street address BUT not in a household
755 // require match on city and state as well
757 SELECT r1.id as master_id,
758 r1.civicrm_primary_id as master_contact_id,
759 r1.postal_greeting as master_postal_greeting,
760 r1.postal_greeting_id as master_postal_greeting_id,
761 r1.addressee as master_addressee,
762 r1.addressee_id as master_addressee_id,
764 r2.civicrm_primary_id as copy_contact_id,
765 r2.postal_greeting as copy_postal_greeting,
766 r2.postal_greeting_id as copy_postal_greeting_id,
767 r2.addressee as copy_addressee,
768 r2.addressee_id as copy_addressee_id
770 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
771 r1.city = r2.city AND
772 r1.state_province_id = r2.state_province_id )
773 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
774 AND ( r2.household_name IS NULL OR r2.household_name = '' )
775 AND ( r1.street_address != '' )
779 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
781 // unset ids from $merge already present in $linkedMerge
782 foreach ($linkedMerge as $masterID => $values) {
783 $keys = array($masterID);
784 $keys = array_merge($keys, array_keys($values['copy']));
785 foreach ($merge as $mid => $vals) {
786 if (in_array($mid, $keys)) {
790 foreach ($values['copy'] as $copyId) {
791 if (in_array($copyId, $keys)) {
792 unset($merge[$mid]['copy'][$copyId]);
798 $merge = $merge +
$linkedMerge;
800 foreach ($merge as $masterID => $values) {
803 SET addressee = %1, postal_greeting = %2, email_greeting = %3
807 1 => array($values['addressee'], 'String'),
808 2 => array($values['postalGreeting'], 'String'),
809 3 => array($values['emailGreeting'], 'String'),
810 4 => array($masterID, 'Integer'),
812 CRM_Core_DAO
::executeQuery($sql, $params);
815 $deleteIDs = array_keys($values['copy']);
816 $deleteIDString = implode(',', $deleteIDs);
818 DELETE FROM $tableName
819 WHERE id IN ( $deleteIDString )
821 CRM_Core_DAO
::executeQuery($sql);
824 // unset temporary columns that were added for postal mailing format
825 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
826 $unsetKeys = array_keys($sqlColumns);
827 foreach ($unsetKeys as $headerKey => $sqlColKey) {
828 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
829 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
836 * @param int $contactId
837 * @param array $exportParams
841 public static function _replaceMergeTokens($contactId, $exportParams) {
842 $greetings = array();
845 $greetingFields = array(
849 foreach ($greetingFields as $greeting) {
850 if (!empty($exportParams[$greeting])) {
851 $greetingLabel = $exportParams[$greeting];
852 if (empty($contact)) {
857 $contact = civicrm_api('contact', 'get', $values);
859 if (!empty($contact['is_error'])) {
862 $contact = $contact['values'][$contact['id']];
865 $tokens = array('contact' => $greetingLabel);
866 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
873 * The function unsets static part of the string, if token is the dynamic part.
875 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
876 * i.e 'Hello Alan' => converted to => 'Alan'
878 * @param string $parsedString
879 * @param string $defaultGreeting
880 * @param bool $addressMergeGreetings
881 * @param string $greetingType
885 public static function _trimNonTokens(
886 &$parsedString, $defaultGreeting,
887 $addressMergeGreetings, $greetingType = 'postal_greeting'
889 if (!empty($addressMergeGreetings[$greetingType])) {
890 $greetingLabel = $addressMergeGreetings[$greetingType];
892 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
894 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
895 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
896 foreach ($stringsToBeReplaced as $key => $string) {
898 $stringsToBeReplaced[$key] = ltrim($string);
900 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
902 return $parsedString;
907 * @param array $exportParams
908 * @param bool $sharedAddress
912 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
913 static $contactGreetingTokens = array();
915 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
916 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
918 $merge = $parents = array();
919 $dao = CRM_Core_DAO
::executeQuery($sql);
921 while ($dao->fetch()) {
922 $masterID = $dao->master_id
;
923 $copyID = $dao->copy_id
;
924 $masterPostalGreeting = $dao->master_postal_greeting
;
925 $masterAddressee = $dao->master_addressee
;
926 $copyAddressee = $dao->copy_addressee
;
928 if (!$sharedAddress) {
929 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
930 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
932 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
933 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
935 $masterAddressee = CRM_Utils_Array
::value('addressee',
936 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
939 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
940 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
942 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
943 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
945 $copyAddressee = CRM_Utils_Array
::value('addressee',
946 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
950 if (!isset($merge[$masterID])) {
951 // check if this is an intermediate child
952 // this happens if there are 3 or more matches a,b, c
953 // the above query will return a, b / a, c / b, c
954 // we might be doing a bit more work, but for now its ok, unless someone
955 // knows how to fix the query above
956 if (isset($parents[$masterID])) {
957 $masterID = $parents[$masterID];
960 $merge[$masterID] = array(
961 'addressee' => $masterAddressee,
963 'postalGreeting' => $masterPostalGreeting,
965 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
968 $parents[$copyID] = $masterID;
970 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
972 if (!empty($exportParams['postal_greeting_other']) &&
973 count($merge[$masterID]['copy']) >= 1
975 // use static greetings specified if no of contacts > 2
976 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
978 elseif ($copyPostalGreeting) {
979 self
::_trimNonTokens($copyPostalGreeting,
980 $postalOptions[$dao->copy_postal_greeting_id
],
983 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
984 // if there happens to be a duplicate, remove it
985 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
988 if (!empty($exportParams['addressee_other']) &&
989 count($merge[$masterID]['copy']) >= 1
991 // use static greetings specified if no of contacts > 2
992 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
994 elseif ($copyAddressee) {
995 self
::_trimNonTokens($copyAddressee,
996 $addresseeOptions[$dao->copy_addressee_id
],
997 $exportParams, 'addressee'
999 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1002 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1009 * Merge household record into the individual record
1012 * @param string $exportTempTable
1013 * Temporary temp table that stores the records.
1014 * @param array $sqlColumns
1015 * Array of names of the table columns of the temp table.
1016 * @param string $prefix
1017 * Name of the relationship type that is prefixed to the table columns.
1019 public static function mergeSameHousehold($exportTempTable, &$sqlColumns, $prefix) {
1020 $prefixColumn = $prefix . '_';
1021 $replaced = array();
1023 // name map of the non standard fields in header rows & sql columns
1024 $mappingFields = array(
1025 'civicrm_primary_id' => 'id',
1026 'provider_id' => 'im_service_provider',
1027 'phone_type_id' => 'phone_type',
1030 //figure out which columns are to be replaced by which ones
1031 foreach ($sqlColumns as $columnNames => $dontCare) {
1032 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1033 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1036 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1038 if (!empty($sqlColumns[$householdColName])) {
1039 $replaced[$columnNames] = $householdColName;
1043 $query = "UPDATE $exportTempTable SET ";
1046 foreach ($replaced as $from => $to) {
1047 $clause[] = "$from = $to ";
1048 unset($sqlColumns[$to]);
1050 $query .= implode(",\n", $clause);
1051 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1053 CRM_Core_DAO
::executeQuery($query);
1055 //drop the table columns that store redundant household info
1056 $dropQuery = "ALTER TABLE $exportTempTable ";
1057 foreach ($replaced as $householdColumns) {
1058 $dropClause[] = " DROP $householdColumns ";
1060 $dropQuery .= implode(",\n", $dropClause);
1062 CRM_Core_DAO
::executeQuery($dropQuery);
1064 // also drop the temp table if exists
1065 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1066 CRM_Core_DAO
::executeQuery($sql);
1068 // clean up duplicate records
1070 CREATE TABLE {$exportTempTable}_temp SELECT *
1071 FROM {$exportTempTable}
1072 GROUP BY civicrm_primary_id ";
1074 CRM_Core_DAO
::executeQuery($query);
1076 $query = "DROP TABLE $exportTempTable";
1077 CRM_Core_DAO
::executeQuery($query);
1079 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1080 CRM_Core_DAO
::executeQuery($query);
1084 * @param $exportTempTable
1085 * @param $headerRows
1086 * @param $sqlColumns
1087 * @param \CRM_Export_BAO_ExportProcessor $processor
1089 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor) {
1090 $exportMode = $processor->getExportMode();
1091 $writeHeader = TRUE;
1093 $limit = self
::EXPORT_ROW_COUNT
;
1095 $query = "SELECT * FROM $exportTempTable";
1098 $limitQuery = $query . "
1099 LIMIT $offset, $limit
1101 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1107 $componentDetails = array();
1108 while ($dao->fetch()) {
1111 foreach ($sqlColumns as $column => $dontCare) {
1112 $row[$column] = $dao->$column;
1114 $componentDetails[] = $row;
1116 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
1123 $writeHeader = FALSE;
1129 * Manipulate header rows for relationship fields.
1131 * @param $headerRows
1133 public static function manipulateHeaderRows(&$headerRows) {
1134 foreach ($headerRows as & $header) {
1135 $split = explode('-', $header);
1136 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1137 $split[0] = $relationTypeName;
1138 $header = implode('-', $split);
1144 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1145 * or have no street address
1146 * @param $exportTempTable
1147 * @param $headerRows
1148 * @param $sqlColumns
1149 * @param $exportParams
1151 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1152 $whereClause = array();
1154 if (array_key_exists('is_deceased', $sqlColumns)) {
1155 $whereClause[] = 'is_deceased = 1';
1158 if (array_key_exists('do_not_mail', $sqlColumns)) {
1159 $whereClause[] = 'do_not_mail = 1';
1162 if (array_key_exists('street_address', $sqlColumns)) {
1163 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1165 // check for supplemental_address_1
1166 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1167 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1168 'address_options', TRUE, NULL, TRUE
1170 if (!empty($addressOptions['supplemental_address_1'])) {
1171 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1172 // enclose it again, since we are doing an AND in between a set of ORs
1173 $addressWhereClause = "( $addressWhereClause )";
1177 $whereClause[] = $addressWhereClause;
1180 if (!empty($whereClause)) {
1181 $whereClause = implode(' OR ', $whereClause);
1184 FROM $exportTempTable
1185 WHERE {$whereClause}";
1186 CRM_Core_DAO
::singleValueQuery($query);
1189 // unset temporary columns that were added for postal mailing format
1190 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1191 $unsetKeys = array_keys($sqlColumns);
1192 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1193 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1194 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1201 * Build componentPayment fields.
1203 * This is no longer used by export but BAO_Mapping still calls it & we
1204 * should find a generic way to handle this or move this to that class.
1208 public static function componentPaymentFields() {
1209 static $componentPaymentFields;
1210 if (!isset($componentPaymentFields)) {
1211 $componentPaymentFields = array(
1212 'componentPaymentField_total_amount' => ts('Total Amount'),
1213 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1214 'componentPaymentField_received_date' => ts('Date Received'),
1215 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1216 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1219 return $componentPaymentFields;
1223 * Set the definition for the header rows and sql columns based on the field to output.
1225 * @param string $field
1226 * @param array $headerRows
1227 * @param \CRM_Export_BAO_ExportProcessor $processor
1231 public static function setHeaderRows($field, $headerRows, $processor) {
1233 $queryFields = $processor->getQueryFields();
1234 if (substr($field, -11) == 'campaign_id') {
1235 // @todo - set this correctly in the xml rather than here.
1236 $headerRows[] = ts('Campaign ID');
1238 elseif ($processor->isMergeSameHousehold() && $field === 'id') {
1239 $headerRows[] = ts('Household ID');
1241 elseif (isset($queryFields[$field]['title'])) {
1242 $headerRows[] = $queryFields[$field]['title'];
1244 elseif ($processor->isExportPaymentFields() && array_key_exists($field, $processor->getcomponentPaymentFields())) {
1245 $headerRows[] = CRM_Utils_Array
::value($field, $processor->getcomponentPaymentFields());
1248 $headerRows[] = $field;
1255 * Get the various arrays that we use to structure our output.
1257 * The extraction of these has been moved to a separate function for clarity and so that
1258 * tests can be added - in particular on the $outputHeaders array.
1260 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1261 * as a step on the refactoring path rather than how it should be.
1263 * @param array $returnProperties
1264 * @param \CRM_Export_BAO_ExportProcessor $processor
1267 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1268 * alias for the field generated by BAO_Query object.
1269 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1270 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1271 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1272 * I'm too embarassed to discuss here.
1274 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1275 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1276 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1277 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1278 * - a) the function used is more efficient or
1279 * - b) this code is old & outdated. Submit your answers to circular bin or better
1280 * yet find a way to comment them for posterity.
1282 public static function getExportStructureArrays($returnProperties, $processor) {
1283 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1284 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1285 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1286 $queryFields = $processor->getQueryFields();
1287 foreach ($returnProperties as $key => $value) {
1288 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
1289 $outputColumns[$key] = $value;
1290 $headerRows = self
::setHeaderRows($key, $headerRows, $processor);
1291 self
::sqlColumnDefn($processor, $sqlColumns, $key);
1293 elseif ($processor->isRelationshipTypeKey($key)) {
1294 $outputColumns[$key] = $value;
1296 foreach ($value as $relationField => $relationValue) {
1297 // below block is same as primary block (duplicate)
1298 if (isset($queryFields[$relationField]['title'])) {
1299 $headerName = $field . '-' . $relationField;
1301 if (!$processor->isHouseholdMergeRelationshipTypeKey($field)) {
1302 // Do not add to header row if we are only generating for merge reasons.
1303 $headerRows[] = $headerName;
1306 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1308 elseif ($relationField == 'phone_type_id') {
1309 $headerName = $field . '-' . 'Phone Type';
1310 $headerRows[] = $headerName;
1311 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1313 elseif ($relationField == 'state_province_id') {
1314 $headerName = $field . '-' . 'state_province_id';
1315 $headerRows[] = $headerName;
1316 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1318 elseif (is_array($relationValue) && $relationField == 'location') {
1319 // fix header for location type case
1320 foreach ($relationValue as $ltype => $val) {
1321 foreach (array_keys($val) as $fld) {
1322 $type = explode('-', $fld);
1324 $hdr = "{$ltype}-" . $queryFields[$type[0]]['title'];
1326 if (!empty($type[1])) {
1327 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1328 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $type[1]);
1330 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1331 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_IM', 'provider_id', $type[1]);
1334 $headerName = $field . '-' . $hdr;
1335 $headerRows[] = $headerName;
1336 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1341 self
::manipulateHeaderRows($headerRows);
1344 foreach ($value as $locationType => $locationFields) {
1345 foreach (array_keys($locationFields) as $locationFieldName) {
1346 $type = explode('-', $locationFieldName);
1348 $actualDBFieldName = $type[0];
1349 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1350 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1352 if (!empty($type[1])) {
1353 $daoFieldName .= "-" . $type[1];
1354 if ($actualDBFieldName == 'phone') {
1355 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1357 elseif ($actualDBFieldName == 'im') {
1358 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1361 if ($type[0] == 'im_provider') {
1362 // Warning: shame inducing hack.
1363 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1365 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1366 $headerRows = self
::setHeaderRows($outputFieldName, $headerRows, $processor);
1367 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1368 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1369 $metadata[$daoFieldName] = array('context' => 'country');
1371 if ($actualDBFieldName == 'state_province') {
1372 $metadata[$daoFieldName] = array('context' => 'province');
1374 $outputColumns[$daoFieldName] = TRUE;
1379 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1383 * Get the values of linked household contact.
1385 * @param CRM_Core_DAO $relDAO
1386 * @param array $value
1387 * @param string $field
1390 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1391 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1392 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1393 $i18n = CRM_Core_I18n
::singleton();
1394 $field = $field . '_';
1396 foreach ($value as $relationField => $relationValue) {
1397 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1398 $fieldValue = $relDAO->$relationField;
1399 if ($relationField == 'phone_type_id') {
1400 $fieldValue = $phoneTypes[$relationValue];
1402 elseif ($relationField == 'provider_id') {
1403 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1406 elseif (is_object($relDAO) && in_array($relationField, array(
1412 //special case for greeting replacement
1413 $fldValue = "{$relationField}_display";
1414 $fieldValue = $relDAO->$fldValue;
1417 elseif (is_object($relDAO) && $relationField == 'state_province') {
1418 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1420 elseif (is_object($relDAO) && $relationField == 'country') {
1421 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1426 $relPrefix = $field . $relationField;
1428 if (is_object($relDAO) && $relationField == 'id') {
1429 $row[$relPrefix] = $relDAO->contact_id
;
1431 elseif (is_array($relationValue) && $relationField == 'location') {
1432 foreach ($relationValue as $ltype => $val) {
1433 // If the location name has a space in it the we need to handle that. This
1434 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1435 // improve it should be secure in the knowled it will be caught.
1436 $ltype = str_replace(' ', '_', $ltype);
1437 foreach (array_keys($val) as $fld) {
1438 $type = explode('-', $fld);
1439 $fldValue = "{$ltype}-" . $type[0];
1440 if (!empty($type[1])) {
1441 $fldValue .= "-" . $type[1];
1443 // CRM-3157: localise country, region (both have ‘country’ context)
1444 // and state_province (‘province’ context)
1446 case (!is_object($relDAO)):
1447 $row[$field . '_' . $fldValue] = '';
1450 case in_array('country', $type):
1451 case in_array('world_region', $type):
1452 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1453 array('context' => 'country')
1457 case in_array('state_province', $type):
1458 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1459 array('context' => 'province')
1464 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1470 elseif (isset($fieldValue) && $fieldValue != '') {
1471 //check for custom data
1472 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1473 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1476 //normal relationship fields
1477 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1478 switch ($relationField) {
1480 case 'world_region':
1481 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1484 case 'state_province':
1485 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1489 $row[$relPrefix] = $fieldValue;
1495 // if relation field is empty or null
1496 $row[$relPrefix] = '';
1502 * Get the ids that we want to get related contact details for.
1505 * @param int $exportMode
1509 protected static function getIDsForRelatedContact($ids, $exportMode) {
1510 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1513 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1515 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1516 $dao = CRM_Core_DAO
::executeQuery("
1517 SELECT contact_id FROM civicrm_activity_contact
1518 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1519 record_type_id = {$sourceID}
1522 while ($dao->fetch()) {
1523 $relIDs[] = $dao->contact_id
;
1527 $component = self
::exportComponent($exportMode);
1529 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1530 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1533 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1540 * @param \CRM_Export_BAO_ExportProcessor $processor
1541 * @param $componentTable
1543 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1544 $allRelContactArray = $relationQuery = array();
1545 $queryMode = $processor->getQueryMode();
1546 $exportMode = $processor->getExportMode();
1548 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1549 $allRelContactArray[$relationshipKey] = array();
1550 // build Query for each relationship
1551 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1552 NULL, FALSE, FALSE, $queryMode
1554 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1556 list($id, $direction) = explode('_', $relationshipKey, 2);
1557 // identify the relationship direction
1558 $contactA = 'contact_id_a';
1559 $contactB = 'contact_id_b';
1560 if ($direction == 'b_a') {
1561 $contactA = 'contact_id_b';
1562 $contactB = 'contact_id_a';
1564 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1566 $relationshipJoin = $relationshipClause = '';
1567 if (!$selectAll && $componentTable) {
1568 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1570 elseif (!empty($relIDs)) {
1571 $relID = implode(',', $relIDs);
1572 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1575 $relationFrom = " {$relationFrom}
1576 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1577 {$relationshipJoin} ";
1579 //check for active relationship status only
1580 $today = date('Ymd');
1581 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1582 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1583 CRM_Core_DAO
::disableFullGroupByMode();
1584 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1585 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1587 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1588 CRM_Core_DAO
::reenableFullGroupByMode();
1590 while ($allRelContactDAO->fetch()) {
1591 $relationQuery->convertToPseudoNames($allRelContactDAO);
1593 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1594 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1595 foreach (array_keys($relationReturnProperties) as $property) {
1596 if ($property === 'location') {
1597 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1598 // $processor->setRelationshipValue from fetchRelationshipDetails
1599 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1600 foreach (array_keys($locationValues) as $locationValue) {
1601 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1602 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1607 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);