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 \CRM_Export_BAO_ExportProcessor $processor
696 * @param array $exportParams
697 * @param bool $sharedAddress
701 public static function _buildMasterCopyArray($processor, $sql, $exportParams, $sharedAddress = FALSE) {
702 static $contactGreetingTokens = [];
704 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
705 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
707 $merge = $parents = [];
708 $dao = CRM_Core_DAO
::executeQuery($sql);
710 while ($dao->fetch()) {
711 $masterID = $dao->master_id
;
712 $copyID = $dao->copy_id
;
713 $masterPostalGreeting = $dao->master_postal_greeting
;
714 $masterAddressee = $dao->master_addressee
;
715 $copyAddressee = $dao->copy_addressee
;
717 if (!$sharedAddress) {
718 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
719 $contactGreetingTokens[$dao->master_contact_id
] = $processor->replaceMergeTokens($dao->master_contact_id
, $exportParams);
721 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
722 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
724 $masterAddressee = CRM_Utils_Array
::value('addressee',
725 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
728 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
729 $contactGreetingTokens[$dao->copy_contact_id
] = $processor->replaceMergeTokens($dao->copy_contact_id
, $exportParams);
731 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
732 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
734 $copyAddressee = CRM_Utils_Array
::value('addressee',
735 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
739 if (!isset($merge[$masterID])) {
740 // check if this is an intermediate child
741 // this happens if there are 3 or more matches a,b, c
742 // the above query will return a, b / a, c / b, c
743 // we might be doing a bit more work, but for now its ok, unless someone
744 // knows how to fix the query above
745 if (isset($parents[$masterID])) {
746 $masterID = $parents[$masterID];
749 $merge[$masterID] = [
750 'addressee' => $masterAddressee,
752 'postalGreeting' => $masterPostalGreeting,
754 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
757 $parents[$copyID] = $masterID;
759 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
761 if (!empty($exportParams['postal_greeting_other']) &&
762 count($merge[$masterID]['copy']) >= 1
764 // use static greetings specified if no of contacts > 2
765 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
767 elseif ($copyPostalGreeting) {
768 $processor->trimNonTokensFromAddressString($copyPostalGreeting,
769 $postalOptions[$dao->copy_postal_greeting_id
],
772 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
773 // if there happens to be a duplicate, remove it
774 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
777 if (!empty($exportParams['addressee_other']) &&
778 count($merge[$masterID]['copy']) >= 1
780 // use static greetings specified if no of contacts > 2
781 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
783 elseif ($copyAddressee) {
784 $processor->trimNonTokensFromAddressString($copyAddressee,
785 $addresseeOptions[$dao->copy_addressee_id
],
786 $exportParams, 'addressee'
788 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
791 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
800 * @param \CRM_Export_BAO_ExportProcessor $processor
802 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
803 $exportTempTable = $processor->getTemporaryTable();
804 $exportMode = $processor->getExportMode();
807 $limit = self
::EXPORT_ROW_COUNT
;
809 $query = "SELECT * FROM $exportTempTable";
812 $limitQuery = $query . "
813 LIMIT $offset, $limit
815 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
821 $componentDetails = [];
822 while ($dao->fetch()) {
825 foreach ($sqlColumns as $column => $dontCare) {
826 $row[$column] = $dao->$column;
828 $componentDetails[] = $row;
830 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
837 $writeHeader = FALSE;
843 * Build componentPayment fields.
845 * This is no longer used by export but BAO_Mapping still calls it & we
846 * should find a generic way to handle this or move this to that class.
850 public static function componentPaymentFields() {
851 static $componentPaymentFields;
852 if (!isset($componentPaymentFields)) {
853 $componentPaymentFields = [
854 'componentPaymentField_total_amount' => ts('Total Amount'),
855 'componentPaymentField_contribution_status' => ts('Contribution Status'),
856 'componentPaymentField_received_date' => ts('Date Received'),
857 'componentPaymentField_payment_instrument' => ts('Payment Method'),
858 'componentPaymentField_transaction_id' => ts('Transaction ID'),
861 return $componentPaymentFields;
865 * Get the various arrays that we use to structure our output.
867 * The extraction of these has been moved to a separate function for clarity and so that
868 * tests can be added - in particular on the $outputHeaders array.
870 * However it still feels a bit like something that I'm too polite to write down and this should be seen
871 * as a step on the refactoring path rather than how it should be.
873 * @param \CRM_Export_BAO_ExportProcessor $processor
876 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
877 * alias for the field generated by BAO_Query object.
878 * - headerRows Array of the column header strings to put in the csv header - non-associative.
879 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
880 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
881 * I'm too embarassed to discuss here.
883 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
884 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
885 * in the main DAO loop is done once per row & that coule be 100,000 times.)
886 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
887 * - a) the function used is more efficient or
888 * - b) this code is old & outdated. Submit your answers to circular bin or better
889 * yet find a way to comment them for posterity.
891 public static function getExportStructureArrays($processor) {
892 $outputColumns = $metadata = [];
893 $queryFields = $processor->getQueryFields();
894 foreach ($processor->getReturnProperties() as $key => $value) {
895 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
896 $outputColumns[$key] = $value;
897 $processor->addOutputSpecification($key);
899 elseif ($processor->isRelationshipTypeKey($key)) {
900 $outputColumns[$key] = $value;
901 foreach ($value as $relationField => $relationValue) {
902 // below block is same as primary block (duplicate)
903 if (isset($queryFields[$relationField]['title'])) {
904 $processor->addOutputSpecification($relationField, $key);
906 elseif (is_array($relationValue) && $relationField == 'location') {
907 // fix header for location type case
908 foreach ($relationValue as $ltype => $val) {
909 foreach (array_keys($val) as $fld) {
910 $type = explode('-', $fld);
911 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
918 foreach ($value as $locationType => $locationFields) {
919 foreach (array_keys($locationFields) as $locationFieldName) {
920 $type = explode('-', $locationFieldName);
922 $actualDBFieldName = $type[0];
923 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
925 if (!empty($type[1])) {
926 $daoFieldName .= "-" . $type[1];
928 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
929 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
930 $outputColumns[$daoFieldName] = TRUE;
935 return [$outputColumns, $metadata];
939 * Get the values of linked household contact.
941 * @param CRM_Core_DAO $relDAO
942 * @param array $value
943 * @param string $field
946 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
947 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
948 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
949 $i18n = CRM_Core_I18n
::singleton();
950 $field = $field . '_';
952 foreach ($value as $relationField => $relationValue) {
953 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
954 $fieldValue = $relDAO->$relationField;
955 if ($relationField == 'phone_type_id') {
956 $fieldValue = $phoneTypes[$relationValue];
958 elseif ($relationField == 'provider_id') {
959 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
962 elseif (is_object($relDAO) && in_array($relationField, [
967 //special case for greeting replacement
968 $fldValue = "{$relationField}_display";
969 $fieldValue = $relDAO->$fldValue;
972 elseif (is_object($relDAO) && $relationField == 'state_province') {
973 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
975 elseif (is_object($relDAO) && $relationField == 'country') {
976 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
981 $relPrefix = $field . $relationField;
983 if (is_object($relDAO) && $relationField == 'id') {
984 $row[$relPrefix] = $relDAO->contact_id
;
986 elseif (is_array($relationValue) && $relationField == 'location') {
987 foreach ($relationValue as $ltype => $val) {
988 // If the location name has a space in it the we need to handle that. This
989 // is kinda hacky but specifically covered in the ExportTest so later efforts to
990 // improve it should be secure in the knowled it will be caught.
991 $ltype = str_replace(' ', '_', $ltype);
992 foreach (array_keys($val) as $fld) {
993 $type = explode('-', $fld);
994 $fldValue = "{$ltype}-" . $type[0];
995 if (!empty($type[1])) {
996 $fldValue .= "-" . $type[1];
998 // CRM-3157: localise country, region (both have ‘country’ context)
999 // and state_province (‘province’ context)
1001 case (!is_object($relDAO)):
1002 $row[$field . '_' . $fldValue] = '';
1005 case in_array('country', $type):
1006 case in_array('world_region', $type):
1007 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1008 ['context' => 'country']
1012 case in_array('state_province', $type):
1013 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1014 ['context' => 'province']
1019 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1025 elseif (isset($fieldValue) && $fieldValue != '') {
1026 //check for custom data
1027 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1028 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1031 //normal relationship fields
1032 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1033 switch ($relationField) {
1035 case 'world_region':
1036 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1039 case 'state_province':
1040 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1044 $row[$relPrefix] = $fieldValue;
1050 // if relation field is empty or null
1051 $row[$relPrefix] = '';
1057 * Get the ids that we want to get related contact details for.
1060 * @param int $exportMode
1064 protected static function getIDsForRelatedContact($ids, $exportMode) {
1065 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1068 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1070 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1071 $dao = CRM_Core_DAO
::executeQuery("
1072 SELECT contact_id FROM civicrm_activity_contact
1073 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1074 record_type_id = {$sourceID}
1077 while ($dao->fetch()) {
1078 $relIDs[] = $dao->contact_id
;
1082 $component = self
::exportComponent($exportMode);
1084 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1085 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1088 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1095 * @param \CRM_Export_BAO_ExportProcessor $processor
1096 * @param $componentTable
1098 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1099 $allRelContactArray = $relationQuery = [];
1100 $queryMode = $processor->getQueryMode();
1101 $exportMode = $processor->getExportMode();
1103 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1104 $allRelContactArray[$relationshipKey] = [];
1105 // build Query for each relationship
1106 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1107 NULL, FALSE, FALSE, $queryMode
1109 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1111 list($id, $direction) = explode('_', $relationshipKey, 2);
1112 // identify the relationship direction
1113 $contactA = 'contact_id_a';
1114 $contactB = 'contact_id_b';
1115 if ($direction == 'b_a') {
1116 $contactA = 'contact_id_b';
1117 $contactB = 'contact_id_a';
1119 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1121 $relationshipJoin = $relationshipClause = '';
1122 if (!$selectAll && $componentTable) {
1123 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1125 elseif (!empty($relIDs)) {
1126 $relID = implode(',', $relIDs);
1127 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1130 $relationFrom = " {$relationFrom}
1131 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1132 {$relationshipJoin} ";
1134 //check for active relationship status only
1135 $today = date('Ymd');
1136 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1137 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1138 CRM_Core_DAO
::disableFullGroupByMode();
1139 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1140 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1142 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1143 CRM_Core_DAO
::reenableFullGroupByMode();
1145 while ($allRelContactDAO->fetch()) {
1146 $relationQuery->convertToPseudoNames($allRelContactDAO);
1148 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1149 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1150 foreach (array_keys($relationReturnProperties) as $property) {
1151 if ($property === 'location') {
1152 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1153 // $processor->setRelationshipValue from fetchRelationshipDetails
1154 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1155 foreach (array_keys($locationValues) as $locationValue) {
1156 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1157 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1162 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);