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 foreach ((array) $fields as $field) {
182 $mappedFields[] = CRM_Core_BAO_Mapping
::getMappingParams([], $field);
185 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
186 // If an Additional Group is selected, then all contacts in that group are
187 // added to the export set (filtering out duplicates).
188 // Really - the calling function could do this ... just saying
189 // @todo take a whip to the calling function.
190 CRM_Core_DAO
::executeQuery("
191 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"
195 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $mappedFields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress);
196 if ($moreReturnProperties) {
197 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
199 $paymentTableId = $processor->getPaymentTableID();
201 if ($processor->getRequestedFields() &&
202 $processor->isPostalableOnly()
204 $exportParams['postal_mailing_export']['temp_columns'] = $processor->getAdditionalFieldsForPostalExport();
207 // rectify params to what proximity search expects if there is a value for prox_distance
209 if (!empty($params)) {
210 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
213 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order);
215 if ($mergeSameHousehold == 1) {
216 $processor->setHouseholdMergeReturnProperties();
219 // This perhaps only needs calling when $mergeSameHousehold == 1
220 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
222 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
223 if (!$selectAll && $componentTable) {
224 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
226 elseif ($componentClause) {
227 $whereClauses[] = $componentClause;
230 // CRM-13982 - check if is deleted
231 foreach ($params as $value) {
232 if ($value[0] == 'contact_is_deleted') {
233 unset($whereClauses['trash_clause']);
238 $where = "WHERE " . implode(' AND ', $whereClauses);
241 $where .= " AND " . implode(' AND ', $whereClauses);
244 $queryString = "$select $from $where $having";
246 $groupBy = self
::getGroupBy($processor, $query);
248 $queryString .= $groupBy;
251 // always add contact_a.id to the ORDER clause
252 // so the order is deterministic
254 if (strpos('contact_a.id', $order) === FALSE) {
255 $order .= ", contact_a.id";
258 list($field, $dir) = explode(' ', $order, 2);
259 $field = trim($field);
260 if (!empty($processor->getReturnProperties()[$field])) {
262 $queryString .= " ORDER BY $order";
266 $addPaymentHeader = FALSE;
268 list($outputColumns, $metadata) = self
::getExportStructureArrays($processor);
270 if ($processor->isMergeSameAddress()) {
271 //make sure the addressee fields are selected
272 //while using merge same address feature
273 // some columns are required for assistance incase they are not already present
274 $exportParams['merge_same_address']['temp_columns'] = $processor->getAdditionalFieldsForSameAddressMerge();
275 // This is silly - we should do this at the point when the array is used...
276 if (isset($exportParams['merge_same_address']['temp_columns']['id'])) {
277 unset($exportParams['merge_same_address']['temp_columns']['id']);
278 $exportParams['merge_same_address']['temp_columns']['civicrm_primary_id'] = 1;
280 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
281 // test exists covering this...
282 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
283 $processor->setColumnAsCalculationOnly($field);
287 $paymentDetails = [];
288 if ($processor->isExportPaymentFields()) {
289 // get payment related in for event and members
290 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
291 //get all payment headers.
292 // If we haven't selected specific payment fields, load in all the
294 if (!$processor->isExportSpecifiedPaymentFields()) {
295 if (!empty($paymentDetails)) {
296 $addPaymentHeader = TRUE;
297 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
298 $processor->addOutputSpecification($paymentField);
304 $componentDetails = [];
306 $rowCount = self
::EXPORT_ROW_COUNT
;
308 // we write to temp table often to avoid using too much memory
313 $headerRows = $processor->getHeaderRows();
314 $sqlColumns = $processor->getSQLColumns();
315 $processor->setTemporaryTable(self
::createTempTable($sqlColumns));
316 $limitReached = FALSE;
318 while (!$limitReached) {
319 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
320 CRM_Core_DAO
::disableFullGroupByMode();
321 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
322 CRM_Core_DAO
::reenableFullGroupByMode();
323 // If this is less than our limit by the end of the iteration we do not need to run the query again to
324 // check if some remain.
325 $rowsThisIteration = 0;
327 while ($iterationDAO->fetch()) {
329 $rowsThisIteration++
;
330 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
331 if ($row === FALSE) {
335 // add component info
336 // write the row to a file
337 $componentDetails[] = $row;
339 // output every $tempRowCount rows
340 if ($count %
$tempRowCount == 0) {
341 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
342 $componentDetails = [];
345 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
346 $limitReached = TRUE;
348 $offset +
= $rowCount;
351 if ($processor->getTemporaryTable()) {
352 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
354 // do merge same address and merge same household processing
355 if ($mergeSameAddress) {
356 self
::mergeSameAddress($processor, $sqlColumns, $exportParams);
360 $table = $processor->getTemporaryTable();
361 CRM_Utils_Hook
::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
362 if ($table !== $processor->getTemporaryTable()) {
363 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
364 $processor->setTemporaryTable($table);
367 // In order to be able to write a unit test against this function we need to suppress
368 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
369 if (empty($exportParams['suppress_csv_for_testing'])) {
370 self
::writeCSVFromTable($headerRows, $sqlColumns, $processor);
373 // return tableName sqlColumns headerRows in test context
374 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
377 // delete the export temp table and component table
378 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
379 CRM_Core_DAO
::executeQuery($sql);
380 CRM_Core_DAO
::reenableFullGroupByMode();
381 CRM_Utils_System
::civiExit(0, ['processor' => $processor]);
384 CRM_Core_DAO
::reenableFullGroupByMode();
385 throw new CRM_Core_Exception(ts('No records to export'));
390 * Handle import error file creation.
392 public static function invoke() {
393 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
394 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
395 if (empty($parserName) ||
empty($type)) {
399 // clean and ensure parserName is a valid string
400 $parserName = CRM_Utils_String
::munge($parserName);
401 $parserClass = explode('_', $parserName);
403 // make sure parserClass is in the CRM namespace and
404 // at least 3 levels deep
405 if ($parserClass[0] == 'CRM' &&
406 count($parserClass) >= 3
408 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
409 // ensure the functions exists
410 if (method_exists($parserName, 'errorFileName') &&
411 method_exists($parserName, 'saveFileName')
413 $errorFileName = $parserName::errorFileName($type);
414 $saveFileName = $parserName::saveFileName($type);
415 if (!empty($errorFileName) && !empty($saveFileName)) {
416 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
417 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
418 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
419 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
420 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
422 readfile($errorFileName);
426 CRM_Utils_System
::civiExit();
430 * @param $customSearchClass
434 public static function exportCustom($customSearchClass, $formValues, $order) {
435 $ext = CRM_Extension_System
::singleton()->getMapper();
436 if (!$ext->isExtensionClass($customSearchClass)) {
437 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
440 require_once $ext->classToPath($customSearchClass);
442 $search = new $customSearchClass($formValues);
444 $includeContactIDs = FALSE;
445 if ($formValues['radio_ts'] == 'ts_sel') {
446 $includeContactIDs = TRUE;
449 $sql = $search->all(0, 0, $order, $includeContactIDs);
451 $columns = $search->columns();
453 $header = array_keys($columns);
454 $fields = array_values($columns);
457 $dao = CRM_Core_DAO
::executeQuery($sql);
459 if (method_exists($search, 'alterRow')) {
462 while ($dao->fetch()) {
465 foreach ($fields as $field) {
466 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
467 $row[$field] = $dao->$unqualified_field;
470 $search->alterRow($row);
475 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
476 CRM_Utils_System
::civiExit();
480 * @param \CRM_Export_BAO_ExportProcessor $processor
484 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
485 $tableName = $processor->getTemporaryTable();
486 if (empty($details)) {
495 $id = CRM_Core_DAO
::singleValueQuery($sql);
502 foreach ($details as $row) {
504 $valueString = [$id];
505 foreach ($row as $value) {
507 $valueString[] = "''";
510 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
513 $sqlClause[] = '(' . implode(',', $valueString) . ')';
515 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
516 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
518 $sqlValueString = implode(",\n", $sqlClause);
521 INSERT INTO $tableName $sqlColumnString
522 VALUES $sqlValueString
524 CRM_Core_DAO
::executeQuery($sql);
532 public static function createTempTable($sqlColumns) {
533 //creating a temporary table for the search result that need be exported
534 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
536 // also create the sql table
537 $exportTempTable->drop();
539 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
540 if (!empty($sqlColumns)) {
541 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
544 $sql .= "\n PRIMARY KEY ( id )";
546 // add indexes for street_address and household_name if present
550 'civicrm_primary_id',
553 foreach ($addIndices as $index) {
554 if (isset($sqlColumns[$index])) {
556 INDEX index_{$index}( $index )
561 $exportTempTable->createWithColumns($sql);
562 return $exportTempTable->getName();
566 * @param \CRM_Export_BAO_ExportProcessor $processor
568 * @param array $exportParams
570 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
571 $greetingOptions = CRM_Export_Form_Select
::getGreetingOptions();
573 if (!empty($greetingOptions)) {
574 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
575 foreach ($greetingOptions as $key => $value) {
576 if ($option = CRM_Utils_Array
::value($key, $exportParams)) {
577 if ($greetingOptions[$key][$option] == ts('Other')) {
578 $exportParams[$key] = $exportParams["{$key}_other"];
580 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
581 $exportParams[$key] = '';
584 $exportParams[$key] = $greetingOptions[$key][$option];
589 $tableName = $processor->getTemporaryTable();
590 // check if any records are present based on if they have used shared address feature,
591 // and not based on if city / state .. matches.
593 SELECT r1.id as copy_id,
594 r1.civicrm_primary_id as copy_contact_id,
595 r1.addressee as copy_addressee,
596 r1.addressee_id as copy_addressee_id,
597 r1.postal_greeting as copy_postal_greeting,
598 r1.postal_greeting_id as copy_postal_greeting_id,
600 r2.civicrm_primary_id as master_contact_id,
601 r2.postal_greeting as master_postal_greeting,
602 r2.postal_greeting_id as master_postal_greeting_id,
603 r2.addressee as master_addressee,
604 r2.addressee_id as master_addressee_id
606 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
607 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
609 $linkedMerge = self
::_buildMasterCopyArray($processor, $sql, $exportParams, TRUE);
611 // find all the records that have the same street address BUT not in a household
612 // require match on city and state as well
614 SELECT r1.id as master_id,
615 r1.civicrm_primary_id as master_contact_id,
616 r1.postal_greeting as master_postal_greeting,
617 r1.postal_greeting_id as master_postal_greeting_id,
618 r1.addressee as master_addressee,
619 r1.addressee_id as master_addressee_id,
621 r2.civicrm_primary_id as copy_contact_id,
622 r2.postal_greeting as copy_postal_greeting,
623 r2.postal_greeting_id as copy_postal_greeting_id,
624 r2.addressee as copy_addressee,
625 r2.addressee_id as copy_addressee_id
627 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
628 r1.city = r2.city AND
629 r1.state_province_id = r2.state_province_id )
630 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
631 AND ( r2.household_name IS NULL OR r2.household_name = '' )
632 AND ( r1.street_address != '' )
636 $merge = self
::_buildMasterCopyArray($processor, $sql, $exportParams);
638 // unset ids from $merge already present in $linkedMerge
639 foreach ($linkedMerge as $masterID => $values) {
641 $keys = array_merge($keys, array_keys($values['copy']));
642 foreach ($merge as $mid => $vals) {
643 if (in_array($mid, $keys)) {
647 foreach ($values['copy'] as $copyId) {
648 if (in_array($copyId, $keys)) {
649 unset($merge[$mid]['copy'][$copyId]);
655 $merge = $merge +
$linkedMerge;
657 foreach ($merge as $masterID => $values) {
660 SET addressee = %1, postal_greeting = %2, email_greeting = %3
664 1 => [$values['addressee'], 'String'],
665 2 => [$values['postalGreeting'], 'String'],
666 3 => [$values['emailGreeting'], 'String'],
667 4 => [$masterID, 'Integer'],
669 CRM_Core_DAO
::executeQuery($sql, $params);
672 $deleteIDs = array_keys($values['copy']);
673 $deleteIDString = implode(',', $deleteIDs);
675 DELETE FROM $tableName
676 WHERE id IN ( $deleteIDString )
678 CRM_Core_DAO
::executeQuery($sql);
681 // unset temporary columns that were added for postal mailing format
682 // @todo - this part is pretty close to ready to be removed....
683 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
684 $unsetKeys = array_keys($sqlColumns);
685 foreach ($unsetKeys as $headerKey => $sqlColKey) {
686 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
687 unset($sqlColumns[$sqlColKey]);
694 * @param int $contactId
695 * @param array $exportParams
699 public static function _replaceMergeTokens($contactId, $exportParams) {
707 foreach ($greetingFields as $greeting) {
708 if (!empty($exportParams[$greeting])) {
709 $greetingLabel = $exportParams[$greeting];
710 if (empty($contact)) {
715 $contact = civicrm_api('contact', 'get', $values);
717 if (!empty($contact['is_error'])) {
720 $contact = $contact['values'][$contact['id']];
723 $tokens = ['contact' => $greetingLabel];
724 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
731 * @param \CRM_Export_BAO_ExportProcessor $processor
733 * @param array $exportParams
734 * @param bool $sharedAddress
738 public static function _buildMasterCopyArray($processor, $sql, $exportParams, $sharedAddress = FALSE) {
739 static $contactGreetingTokens = [];
741 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
742 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
744 $merge = $parents = [];
745 $dao = CRM_Core_DAO
::executeQuery($sql);
747 while ($dao->fetch()) {
748 $masterID = $dao->master_id
;
749 $copyID = $dao->copy_id
;
750 $masterPostalGreeting = $dao->master_postal_greeting
;
751 $masterAddressee = $dao->master_addressee
;
752 $copyAddressee = $dao->copy_addressee
;
754 if (!$sharedAddress) {
755 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
756 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
758 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
759 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
761 $masterAddressee = CRM_Utils_Array
::value('addressee',
762 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
765 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
766 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
768 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
769 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
771 $copyAddressee = CRM_Utils_Array
::value('addressee',
772 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
776 if (!isset($merge[$masterID])) {
777 // check if this is an intermediate child
778 // this happens if there are 3 or more matches a,b, c
779 // the above query will return a, b / a, c / b, c
780 // we might be doing a bit more work, but for now its ok, unless someone
781 // knows how to fix the query above
782 if (isset($parents[$masterID])) {
783 $masterID = $parents[$masterID];
786 $merge[$masterID] = [
787 'addressee' => $masterAddressee,
789 'postalGreeting' => $masterPostalGreeting,
791 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
794 $parents[$copyID] = $masterID;
796 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
798 if (!empty($exportParams['postal_greeting_other']) &&
799 count($merge[$masterID]['copy']) >= 1
801 // use static greetings specified if no of contacts > 2
802 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
804 elseif ($copyPostalGreeting) {
805 $processor->trimNonTokensFromAddressString($copyPostalGreeting,
806 $postalOptions[$dao->copy_postal_greeting_id
],
809 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
810 // if there happens to be a duplicate, remove it
811 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
814 if (!empty($exportParams['addressee_other']) &&
815 count($merge[$masterID]['copy']) >= 1
817 // use static greetings specified if no of contacts > 2
818 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
820 elseif ($copyAddressee) {
821 $processor->trimNonTokensFromAddressString($copyAddressee,
822 $addresseeOptions[$dao->copy_addressee_id
],
823 $exportParams, 'addressee'
825 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
828 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
837 * @param \CRM_Export_BAO_ExportProcessor $processor
839 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
840 $exportTempTable = $processor->getTemporaryTable();
841 $exportMode = $processor->getExportMode();
844 $limit = self
::EXPORT_ROW_COUNT
;
846 $query = "SELECT * FROM $exportTempTable";
849 $limitQuery = $query . "
850 LIMIT $offset, $limit
852 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
858 $componentDetails = [];
859 while ($dao->fetch()) {
862 foreach ($sqlColumns as $column => $dontCare) {
863 $row[$column] = $dao->$column;
865 $componentDetails[] = $row;
867 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
874 $writeHeader = FALSE;
880 * Build componentPayment fields.
882 * This is no longer used by export but BAO_Mapping still calls it & we
883 * should find a generic way to handle this or move this to that class.
887 public static function componentPaymentFields() {
888 static $componentPaymentFields;
889 if (!isset($componentPaymentFields)) {
890 $componentPaymentFields = [
891 'componentPaymentField_total_amount' => ts('Total Amount'),
892 'componentPaymentField_contribution_status' => ts('Contribution Status'),
893 'componentPaymentField_received_date' => ts('Date Received'),
894 'componentPaymentField_payment_instrument' => ts('Payment Method'),
895 'componentPaymentField_transaction_id' => ts('Transaction ID'),
898 return $componentPaymentFields;
902 * Get the various arrays that we use to structure our output.
904 * The extraction of these has been moved to a separate function for clarity and so that
905 * tests can be added - in particular on the $outputHeaders array.
907 * However it still feels a bit like something that I'm too polite to write down and this should be seen
908 * as a step on the refactoring path rather than how it should be.
910 * @param \CRM_Export_BAO_ExportProcessor $processor
913 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
914 * alias for the field generated by BAO_Query object.
915 * - headerRows Array of the column header strings to put in the csv header - non-associative.
916 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
917 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
918 * I'm too embarassed to discuss here.
920 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
921 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
922 * in the main DAO loop is done once per row & that coule be 100,000 times.)
923 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
924 * - a) the function used is more efficient or
925 * - b) this code is old & outdated. Submit your answers to circular bin or better
926 * yet find a way to comment them for posterity.
928 public static function getExportStructureArrays($processor) {
929 $outputColumns = $metadata = [];
930 $queryFields = $processor->getQueryFields();
931 foreach ($processor->getReturnProperties() as $key => $value) {
932 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
933 $outputColumns[$key] = $value;
934 $processor->addOutputSpecification($key);
936 elseif ($processor->isRelationshipTypeKey($key)) {
937 $outputColumns[$key] = $value;
938 foreach ($value as $relationField => $relationValue) {
939 // below block is same as primary block (duplicate)
940 if (isset($queryFields[$relationField]['title'])) {
941 $processor->addOutputSpecification($relationField, $key);
943 elseif (is_array($relationValue) && $relationField == 'location') {
944 // fix header for location type case
945 foreach ($relationValue as $ltype => $val) {
946 foreach (array_keys($val) as $fld) {
947 $type = explode('-', $fld);
948 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
955 foreach ($value as $locationType => $locationFields) {
956 foreach (array_keys($locationFields) as $locationFieldName) {
957 $type = explode('-', $locationFieldName);
959 $actualDBFieldName = $type[0];
960 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
962 if (!empty($type[1])) {
963 $daoFieldName .= "-" . $type[1];
965 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
966 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
967 $outputColumns[$daoFieldName] = TRUE;
972 return [$outputColumns, $metadata];
976 * Get the values of linked household contact.
978 * @param CRM_Core_DAO $relDAO
979 * @param array $value
980 * @param string $field
983 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
984 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
985 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
986 $i18n = CRM_Core_I18n
::singleton();
987 $field = $field . '_';
989 foreach ($value as $relationField => $relationValue) {
990 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
991 $fieldValue = $relDAO->$relationField;
992 if ($relationField == 'phone_type_id') {
993 $fieldValue = $phoneTypes[$relationValue];
995 elseif ($relationField == 'provider_id') {
996 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
999 elseif (is_object($relDAO) && in_array($relationField, [
1004 //special case for greeting replacement
1005 $fldValue = "{$relationField}_display";
1006 $fieldValue = $relDAO->$fldValue;
1009 elseif (is_object($relDAO) && $relationField == 'state_province') {
1010 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1012 elseif (is_object($relDAO) && $relationField == 'country') {
1013 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1018 $relPrefix = $field . $relationField;
1020 if (is_object($relDAO) && $relationField == 'id') {
1021 $row[$relPrefix] = $relDAO->contact_id
;
1023 elseif (is_array($relationValue) && $relationField == 'location') {
1024 foreach ($relationValue as $ltype => $val) {
1025 // If the location name has a space in it the we need to handle that. This
1026 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1027 // improve it should be secure in the knowled it will be caught.
1028 $ltype = str_replace(' ', '_', $ltype);
1029 foreach (array_keys($val) as $fld) {
1030 $type = explode('-', $fld);
1031 $fldValue = "{$ltype}-" . $type[0];
1032 if (!empty($type[1])) {
1033 $fldValue .= "-" . $type[1];
1035 // CRM-3157: localise country, region (both have ‘country’ context)
1036 // and state_province (‘province’ context)
1038 case (!is_object($relDAO)):
1039 $row[$field . '_' . $fldValue] = '';
1042 case in_array('country', $type):
1043 case in_array('world_region', $type):
1044 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1045 ['context' => 'country']
1049 case in_array('state_province', $type):
1050 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1051 ['context' => 'province']
1056 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1062 elseif (isset($fieldValue) && $fieldValue != '') {
1063 //check for custom data
1064 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1065 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1068 //normal relationship fields
1069 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1070 switch ($relationField) {
1072 case 'world_region':
1073 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1076 case 'state_province':
1077 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1081 $row[$relPrefix] = $fieldValue;
1087 // if relation field is empty or null
1088 $row[$relPrefix] = '';
1094 * Get the ids that we want to get related contact details for.
1097 * @param int $exportMode
1101 protected static function getIDsForRelatedContact($ids, $exportMode) {
1102 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1105 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1107 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1108 $dao = CRM_Core_DAO
::executeQuery("
1109 SELECT contact_id FROM civicrm_activity_contact
1110 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1111 record_type_id = {$sourceID}
1114 while ($dao->fetch()) {
1115 $relIDs[] = $dao->contact_id
;
1119 $component = self
::exportComponent($exportMode);
1121 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1122 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1125 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1132 * @param \CRM_Export_BAO_ExportProcessor $processor
1133 * @param $componentTable
1135 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1136 $allRelContactArray = $relationQuery = [];
1137 $queryMode = $processor->getQueryMode();
1138 $exportMode = $processor->getExportMode();
1140 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1141 $allRelContactArray[$relationshipKey] = [];
1142 // build Query for each relationship
1143 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1144 NULL, FALSE, FALSE, $queryMode
1146 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1148 list($id, $direction) = explode('_', $relationshipKey, 2);
1149 // identify the relationship direction
1150 $contactA = 'contact_id_a';
1151 $contactB = 'contact_id_b';
1152 if ($direction == 'b_a') {
1153 $contactA = 'contact_id_b';
1154 $contactB = 'contact_id_a';
1156 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1158 $relationshipJoin = $relationshipClause = '';
1159 if (!$selectAll && $componentTable) {
1160 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1162 elseif (!empty($relIDs)) {
1163 $relID = implode(',', $relIDs);
1164 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1167 $relationFrom = " {$relationFrom}
1168 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1169 {$relationshipJoin} ";
1171 //check for active relationship status only
1172 $today = date('Ymd');
1173 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1174 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1175 CRM_Core_DAO
::disableFullGroupByMode();
1176 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1177 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1179 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1180 CRM_Core_DAO
::reenableFullGroupByMode();
1182 while ($allRelContactDAO->fetch()) {
1183 $relationQuery->convertToPseudoNames($allRelContactDAO);
1185 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1186 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1187 foreach (array_keys($relationReturnProperties) as $property) {
1188 if ($property === 'location') {
1189 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1190 // $processor->setRelationshipValue from fetchRelationshipDetails
1191 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1192 foreach (array_keys($locationValues) as $locationValue) {
1193 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1194 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1199 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);