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 array $returnProperties
84 * @param object $query
85 * CRM_Contact_BAO_Query
90 public static function getGroupBy($processor, $returnProperties, $query) {
92 $exportMode = $processor->getExportMode();
93 $queryMode = $processor->getQueryMode();
94 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
95 CRM_Utils_Array
::value('notes', $returnProperties) ||
97 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
99 $groupBy = "contact_a.id";
102 switch ($exportMode) {
103 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
104 $groupBy = 'civicrm_contribution.id';
105 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
106 // especial group by when soft credit columns are included
107 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
111 case CRM_Export_Form_Select
::EVENT_EXPORT
:
112 $groupBy = 'civicrm_participant.id';
115 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
116 $groupBy = "civicrm_membership.id";
120 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
121 $groupBy = "civicrm_activity.id ";
124 return $groupBy ?
' GROUP BY ' . implode(', ', (array) $groupBy) : '';
128 * Get the list the export fields.
130 * @param int $selectAll
131 * User preference while export.
134 * @param array $params
135 * Associated array of fields.
136 * @param string $order
138 * @param array $fields
139 * Associated array of fields.
140 * @param array $moreReturnProperties
141 * Additional return fields.
142 * @param int $exportMode
144 * @param string $componentClause
146 * @param string $componentTable
148 * @param bool $mergeSameAddress
149 * Merge records if they have same address.
150 * @param bool $mergeSameHousehold
151 * Merge records if they belong to the same household.
153 * @param array $exportParams
154 * @param string $queryOperator
157 * An array can be requested from within a unit test.
159 * @throws \CRM_Core_Exception
161 public static function exportComponents(
167 $moreReturnProperties = NULL,
168 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
169 $componentClause = NULL,
170 $componentTable = NULL,
171 $mergeSameAddress = FALSE,
172 $mergeSameHousehold = FALSE,
174 $queryOperator = 'AND'
178 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
179 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
182 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly);
183 $returnProperties = $processor->getReturnProperties();
184 $paymentTableId = $processor->getPaymentTableID();
186 if ($mergeSameAddress) {
187 //make sure the addressee fields are selected
188 //while using merge same address feature
189 $returnProperties['addressee'] = 1;
190 $returnProperties['postal_greeting'] = 1;
191 $returnProperties['email_greeting'] = 1;
192 $returnProperties['street_name'] = 1;
193 $returnProperties['household_name'] = 1;
194 $returnProperties['street_address'] = 1;
195 $returnProperties['city'] = 1;
196 $returnProperties['state_province'] = 1;
198 // some columns are required for assistance incase they are not already present
199 $exportParams['merge_same_address']['temp_columns'] = [];
200 $tempColumns = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
201 foreach ($tempColumns as $column) {
202 if (!array_key_exists($column, $returnProperties)) {
203 $returnProperties[$column] = 1;
204 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
205 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
210 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
211 // If an Additional Group is selected, then all contacts in that group are
212 // added to the export set (filtering out duplicates).
214 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";
215 CRM_Core_DAO
::executeQuery($query);
218 if ($moreReturnProperties) {
220 if (!empty($moreReturnProperties['group'])) {
221 unset($moreReturnProperties['group']);
222 $moreReturnProperties['groups'] = 1;
224 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
227 if ($processor->getRequestedFields() &&
228 $processor->isPostalableOnly()
230 $postalColumns = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
231 $exportParams['postal_mailing_export']['temp_columns'] = [];
232 foreach ($postalColumns as $column) {
233 if (!array_key_exists($column, $returnProperties)) {
234 $returnProperties[$column] = 1;
235 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
240 // rectify params to what proximity search expects if there is a value for prox_distance
242 if (!empty($params)) {
243 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
246 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
248 if ($mergeSameHousehold == 1) {
249 if (empty($returnProperties['id'])) {
250 $returnProperties['id'] = 1;
253 $processor->setHouseholdMergeReturnProperties(array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1)));
256 // This perhaps only needs calling when $mergeSameHousehold == 1
257 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
259 // make sure the groups stuff is included only if specifically specified
260 // by the fields param (CRM-1969), else we limit the contacts outputted to only
261 // ones that are part of a group
262 if (!empty($returnProperties['groups'])) {
263 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
264 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
265 // total hack for export, CRM-3618
266 $from = str_replace($oldClause,
272 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
273 if (!$selectAll && $componentTable) {
274 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
276 elseif ($componentClause) {
277 $whereClauses[] = $componentClause;
280 // CRM-13982 - check if is deleted
281 foreach ($params as $value) {
282 if ($value[0] == 'contact_is_deleted') {
283 unset($whereClauses['trash_clause']);
288 $where = "WHERE " . implode(' AND ', $whereClauses);
291 $where .= " AND " . implode(' AND ', $whereClauses);
294 $queryString = "$select $from $where $having";
296 $groupBy = self
::getGroupBy($processor, $returnProperties, $query);
298 $queryString .= $groupBy;
301 // always add contact_a.id to the ORDER clause
302 // so the order is deterministic
304 if (strpos('contact_a.id', $order) === FALSE) {
305 $order .= ", contact_a.id";
308 list($field, $dir) = explode(' ', $order, 2);
309 $field = trim($field);
310 if (!empty($returnProperties[$field])) {
312 $queryString .= " ORDER BY $order";
316 $addPaymentHeader = FALSE;
318 list($outputColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
320 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
321 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
322 // test exists covering this...
323 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
324 $processor->setColumnAsCalculationOnly($field);
328 $paymentDetails = [];
329 if ($processor->isExportPaymentFields()) {
330 // get payment related in for event and members
331 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
332 //get all payment headers.
333 // If we haven't selected specific payment fields, load in all the
335 if (!$processor->isExportSpecifiedPaymentFields()) {
336 if (!empty($paymentDetails)) {
337 $addPaymentHeader = TRUE;
338 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
339 $processor->addOutputSpecification($paymentField);
345 $componentDetails = [];
347 $rowCount = self
::EXPORT_ROW_COUNT
;
349 // we write to temp table often to avoid using too much memory
354 $headerRows = $processor->getHeaderRows();
355 $sqlColumns = $processor->getSQLColumns();
356 $processor->setTemporaryTable(self
::createTempTable($sqlColumns));
357 $limitReached = FALSE;
359 while (!$limitReached) {
360 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
361 CRM_Core_DAO
::disableFullGroupByMode();
362 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
363 CRM_Core_DAO
::reenableFullGroupByMode();
364 // If this is less than our limit by the end of the iteration we do not need to run the query again to
365 // check if some remain.
366 $rowsThisIteration = 0;
368 while ($iterationDAO->fetch()) {
370 $rowsThisIteration++
;
371 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
372 if ($row === FALSE) {
376 // add component info
377 // write the row to a file
378 $componentDetails[] = $row;
380 // output every $tempRowCount rows
381 if ($count %
$tempRowCount == 0) {
382 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
383 $componentDetails = [];
386 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
387 $limitReached = TRUE;
389 $offset +
= $rowCount;
392 if ($processor->getTemporaryTable()) {
393 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
395 // do merge same address and merge same household processing
396 if ($mergeSameAddress) {
397 self
::mergeSameAddress($processor, $sqlColumns, $exportParams);
401 $table = $processor->getTemporaryTable();
402 CRM_Utils_Hook
::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
403 if ($table !== $processor->getTemporaryTable()) {
404 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
405 $processor->setTemporaryTable($table);
408 // In order to be able to write a unit test against this function we need to suppress
409 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
410 if (empty($exportParams['suppress_csv_for_testing'])) {
411 self
::writeCSVFromTable($headerRows, $sqlColumns, $processor);
414 // return tableName sqlColumns headerRows in test context
415 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
418 // delete the export temp table and component table
419 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
420 CRM_Core_DAO
::executeQuery($sql);
421 CRM_Core_DAO
::reenableFullGroupByMode();
422 CRM_Utils_System
::civiExit(0, ['processor' => $processor]);
425 CRM_Core_DAO
::reenableFullGroupByMode();
426 throw new CRM_Core_Exception(ts('No records to export'));
431 * Handle import error file creation.
433 public static function invoke() {
434 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
435 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
436 if (empty($parserName) ||
empty($type)) {
440 // clean and ensure parserName is a valid string
441 $parserName = CRM_Utils_String
::munge($parserName);
442 $parserClass = explode('_', $parserName);
444 // make sure parserClass is in the CRM namespace and
445 // at least 3 levels deep
446 if ($parserClass[0] == 'CRM' &&
447 count($parserClass) >= 3
449 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
450 // ensure the functions exists
451 if (method_exists($parserName, 'errorFileName') &&
452 method_exists($parserName, 'saveFileName')
454 $errorFileName = $parserName::errorFileName($type);
455 $saveFileName = $parserName::saveFileName($type);
456 if (!empty($errorFileName) && !empty($saveFileName)) {
457 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
458 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
459 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
460 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
461 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
463 readfile($errorFileName);
467 CRM_Utils_System
::civiExit();
471 * @param $customSearchClass
475 public static function exportCustom($customSearchClass, $formValues, $order) {
476 $ext = CRM_Extension_System
::singleton()->getMapper();
477 if (!$ext->isExtensionClass($customSearchClass)) {
478 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
481 require_once $ext->classToPath($customSearchClass);
483 $search = new $customSearchClass($formValues);
485 $includeContactIDs = FALSE;
486 if ($formValues['radio_ts'] == 'ts_sel') {
487 $includeContactIDs = TRUE;
490 $sql = $search->all(0, 0, $order, $includeContactIDs);
492 $columns = $search->columns();
494 $header = array_keys($columns);
495 $fields = array_values($columns);
498 $dao = CRM_Core_DAO
::executeQuery($sql);
500 if (method_exists($search, 'alterRow')) {
503 while ($dao->fetch()) {
506 foreach ($fields as $field) {
507 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
508 $row[$field] = $dao->$unqualified_field;
511 $search->alterRow($row);
516 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
517 CRM_Utils_System
::civiExit();
521 * @param \CRM_Export_BAO_ExportProcessor $processor
525 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
526 $tableName = $processor->getTemporaryTable();
527 if (empty($details)) {
536 $id = CRM_Core_DAO
::singleValueQuery($sql);
543 foreach ($details as $row) {
545 $valueString = [$id];
546 foreach ($row as $value) {
548 $valueString[] = "''";
551 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
554 $sqlClause[] = '(' . implode(',', $valueString) . ')';
556 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
557 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
559 $sqlValueString = implode(",\n", $sqlClause);
562 INSERT INTO $tableName $sqlColumnString
563 VALUES $sqlValueString
565 CRM_Core_DAO
::executeQuery($sql);
573 public static function createTempTable($sqlColumns) {
574 //creating a temporary table for the search result that need be exported
575 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
577 // also create the sql table
578 $exportTempTable->drop();
580 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
581 if (!empty($sqlColumns)) {
582 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
585 $sql .= "\n PRIMARY KEY ( id )";
587 // add indexes for street_address and household_name if present
591 'civicrm_primary_id',
594 foreach ($addIndices as $index) {
595 if (isset($sqlColumns[$index])) {
597 INDEX index_{$index}( $index )
602 $exportTempTable->createWithColumns($sql);
603 return $exportTempTable->getName();
607 * @param \CRM_Export_BAO_ExportProcessor $processor
609 * @param array $exportParams
611 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
612 $tableName = $processor->getTemporaryTable();
613 // check if any records are present based on if they have used shared address feature,
614 // and not based on if city / state .. matches.
616 SELECT r1.id as copy_id,
617 r1.civicrm_primary_id as copy_contact_id,
618 r1.addressee as copy_addressee,
619 r1.addressee_id as copy_addressee_id,
620 r1.postal_greeting as copy_postal_greeting,
621 r1.postal_greeting_id as copy_postal_greeting_id,
623 r2.civicrm_primary_id as master_contact_id,
624 r2.postal_greeting as master_postal_greeting,
625 r2.postal_greeting_id as master_postal_greeting_id,
626 r2.addressee as master_addressee,
627 r2.addressee_id as master_addressee_id
629 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
630 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
632 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
634 // find all the records that have the same street address BUT not in a household
635 // require match on city and state as well
637 SELECT r1.id as master_id,
638 r1.civicrm_primary_id as master_contact_id,
639 r1.postal_greeting as master_postal_greeting,
640 r1.postal_greeting_id as master_postal_greeting_id,
641 r1.addressee as master_addressee,
642 r1.addressee_id as master_addressee_id,
644 r2.civicrm_primary_id as copy_contact_id,
645 r2.postal_greeting as copy_postal_greeting,
646 r2.postal_greeting_id as copy_postal_greeting_id,
647 r2.addressee as copy_addressee,
648 r2.addressee_id as copy_addressee_id
650 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
651 r1.city = r2.city AND
652 r1.state_province_id = r2.state_province_id )
653 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
654 AND ( r2.household_name IS NULL OR r2.household_name = '' )
655 AND ( r1.street_address != '' )
659 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
661 // unset ids from $merge already present in $linkedMerge
662 foreach ($linkedMerge as $masterID => $values) {
664 $keys = array_merge($keys, array_keys($values['copy']));
665 foreach ($merge as $mid => $vals) {
666 if (in_array($mid, $keys)) {
670 foreach ($values['copy'] as $copyId) {
671 if (in_array($copyId, $keys)) {
672 unset($merge[$mid]['copy'][$copyId]);
678 $merge = $merge +
$linkedMerge;
680 foreach ($merge as $masterID => $values) {
683 SET addressee = %1, postal_greeting = %2, email_greeting = %3
687 1 => [$values['addressee'], 'String'],
688 2 => [$values['postalGreeting'], 'String'],
689 3 => [$values['emailGreeting'], 'String'],
690 4 => [$masterID, 'Integer'],
692 CRM_Core_DAO
::executeQuery($sql, $params);
695 $deleteIDs = array_keys($values['copy']);
696 $deleteIDString = implode(',', $deleteIDs);
698 DELETE FROM $tableName
699 WHERE id IN ( $deleteIDString )
701 CRM_Core_DAO
::executeQuery($sql);
704 // unset temporary columns that were added for postal mailing format
705 // @todo - this part is pretty close to ready to be removed....
706 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
707 $unsetKeys = array_keys($sqlColumns);
708 foreach ($unsetKeys as $headerKey => $sqlColKey) {
709 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
710 unset($sqlColumns[$sqlColKey]);
717 * @param int $contactId
718 * @param array $exportParams
722 public static function _replaceMergeTokens($contactId, $exportParams) {
730 foreach ($greetingFields as $greeting) {
731 if (!empty($exportParams[$greeting])) {
732 $greetingLabel = $exportParams[$greeting];
733 if (empty($contact)) {
738 $contact = civicrm_api('contact', 'get', $values);
740 if (!empty($contact['is_error'])) {
743 $contact = $contact['values'][$contact['id']];
746 $tokens = ['contact' => $greetingLabel];
747 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
754 * The function unsets static part of the string, if token is the dynamic part.
756 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
757 * i.e 'Hello Alan' => converted to => 'Alan'
759 * @param string $parsedString
760 * @param string $defaultGreeting
761 * @param bool $addressMergeGreetings
762 * @param string $greetingType
766 public static function _trimNonTokens(
767 &$parsedString, $defaultGreeting,
768 $addressMergeGreetings, $greetingType = 'postal_greeting'
770 if (!empty($addressMergeGreetings[$greetingType])) {
771 $greetingLabel = $addressMergeGreetings[$greetingType];
773 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
775 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
776 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
777 foreach ($stringsToBeReplaced as $key => $string) {
779 $stringsToBeReplaced[$key] = ltrim($string);
781 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
783 return $parsedString;
788 * @param array $exportParams
789 * @param bool $sharedAddress
793 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
794 static $contactGreetingTokens = [];
796 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
797 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
799 $merge = $parents = [];
800 $dao = CRM_Core_DAO
::executeQuery($sql);
802 while ($dao->fetch()) {
803 $masterID = $dao->master_id
;
804 $copyID = $dao->copy_id
;
805 $masterPostalGreeting = $dao->master_postal_greeting
;
806 $masterAddressee = $dao->master_addressee
;
807 $copyAddressee = $dao->copy_addressee
;
809 if (!$sharedAddress) {
810 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
811 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
813 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
814 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
816 $masterAddressee = CRM_Utils_Array
::value('addressee',
817 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
820 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
821 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
823 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
824 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
826 $copyAddressee = CRM_Utils_Array
::value('addressee',
827 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
831 if (!isset($merge[$masterID])) {
832 // check if this is an intermediate child
833 // this happens if there are 3 or more matches a,b, c
834 // the above query will return a, b / a, c / b, c
835 // we might be doing a bit more work, but for now its ok, unless someone
836 // knows how to fix the query above
837 if (isset($parents[$masterID])) {
838 $masterID = $parents[$masterID];
841 $merge[$masterID] = [
842 'addressee' => $masterAddressee,
844 'postalGreeting' => $masterPostalGreeting,
846 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
849 $parents[$copyID] = $masterID;
851 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
853 if (!empty($exportParams['postal_greeting_other']) &&
854 count($merge[$masterID]['copy']) >= 1
856 // use static greetings specified if no of contacts > 2
857 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
859 elseif ($copyPostalGreeting) {
860 self
::_trimNonTokens($copyPostalGreeting,
861 $postalOptions[$dao->copy_postal_greeting_id
],
864 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
865 // if there happens to be a duplicate, remove it
866 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
869 if (!empty($exportParams['addressee_other']) &&
870 count($merge[$masterID]['copy']) >= 1
872 // use static greetings specified if no of contacts > 2
873 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
875 elseif ($copyAddressee) {
876 self
::_trimNonTokens($copyAddressee,
877 $addresseeOptions[$dao->copy_addressee_id
],
878 $exportParams, 'addressee'
880 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
883 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
892 * @param \CRM_Export_BAO_ExportProcessor $processor
894 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
895 $exportTempTable = $processor->getTemporaryTable();
896 $exportMode = $processor->getExportMode();
899 $limit = self
::EXPORT_ROW_COUNT
;
901 $query = "SELECT * FROM $exportTempTable";
904 $limitQuery = $query . "
905 LIMIT $offset, $limit
907 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
913 $componentDetails = [];
914 while ($dao->fetch()) {
917 foreach ($sqlColumns as $column => $dontCare) {
918 $row[$column] = $dao->$column;
920 $componentDetails[] = $row;
922 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
929 $writeHeader = FALSE;
935 * Build componentPayment fields.
937 * This is no longer used by export but BAO_Mapping still calls it & we
938 * should find a generic way to handle this or move this to that class.
942 public static function componentPaymentFields() {
943 static $componentPaymentFields;
944 if (!isset($componentPaymentFields)) {
945 $componentPaymentFields = [
946 'componentPaymentField_total_amount' => ts('Total Amount'),
947 'componentPaymentField_contribution_status' => ts('Contribution Status'),
948 'componentPaymentField_received_date' => ts('Date Received'),
949 'componentPaymentField_payment_instrument' => ts('Payment Method'),
950 'componentPaymentField_transaction_id' => ts('Transaction ID'),
953 return $componentPaymentFields;
957 * Get the various arrays that we use to structure our output.
959 * The extraction of these has been moved to a separate function for clarity and so that
960 * tests can be added - in particular on the $outputHeaders array.
962 * However it still feels a bit like something that I'm too polite to write down and this should be seen
963 * as a step on the refactoring path rather than how it should be.
965 * @param array $returnProperties
966 * @param \CRM_Export_BAO_ExportProcessor $processor
969 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
970 * alias for the field generated by BAO_Query object.
971 * - headerRows Array of the column header strings to put in the csv header - non-associative.
972 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
973 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
974 * I'm too embarassed to discuss here.
976 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
977 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
978 * in the main DAO loop is done once per row & that coule be 100,000 times.)
979 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
980 * - a) the function used is more efficient or
981 * - b) this code is old & outdated. Submit your answers to circular bin or better
982 * yet find a way to comment them for posterity.
984 public static function getExportStructureArrays($returnProperties, $processor) {
985 $outputColumns = $metadata = [];
986 $queryFields = $processor->getQueryFields();
987 foreach ($returnProperties as $key => $value) {
988 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
989 $outputColumns[$key] = $value;
990 $processor->addOutputSpecification($key);
992 elseif ($processor->isRelationshipTypeKey($key)) {
993 $outputColumns[$key] = $value;
994 foreach ($value as $relationField => $relationValue) {
995 // below block is same as primary block (duplicate)
996 if (isset($queryFields[$relationField]['title'])) {
997 $processor->addOutputSpecification($relationField, $key);
999 elseif (is_array($relationValue) && $relationField == 'location') {
1000 // fix header for location type case
1001 foreach ($relationValue as $ltype => $val) {
1002 foreach (array_keys($val) as $fld) {
1003 $type = explode('-', $fld);
1004 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
1011 foreach ($value as $locationType => $locationFields) {
1012 foreach (array_keys($locationFields) as $locationFieldName) {
1013 $type = explode('-', $locationFieldName);
1015 $actualDBFieldName = $type[0];
1016 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1018 if (!empty($type[1])) {
1019 $daoFieldName .= "-" . $type[1];
1021 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
1022 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
1023 $outputColumns[$daoFieldName] = TRUE;
1028 return [$outputColumns, $metadata];
1032 * Get the values of linked household contact.
1034 * @param CRM_Core_DAO $relDAO
1035 * @param array $value
1036 * @param string $field
1039 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1040 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1041 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1042 $i18n = CRM_Core_I18n
::singleton();
1043 $field = $field . '_';
1045 foreach ($value as $relationField => $relationValue) {
1046 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1047 $fieldValue = $relDAO->$relationField;
1048 if ($relationField == 'phone_type_id') {
1049 $fieldValue = $phoneTypes[$relationValue];
1051 elseif ($relationField == 'provider_id') {
1052 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1055 elseif (is_object($relDAO) && in_array($relationField, [
1060 //special case for greeting replacement
1061 $fldValue = "{$relationField}_display";
1062 $fieldValue = $relDAO->$fldValue;
1065 elseif (is_object($relDAO) && $relationField == 'state_province') {
1066 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1068 elseif (is_object($relDAO) && $relationField == 'country') {
1069 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1074 $relPrefix = $field . $relationField;
1076 if (is_object($relDAO) && $relationField == 'id') {
1077 $row[$relPrefix] = $relDAO->contact_id
;
1079 elseif (is_array($relationValue) && $relationField == 'location') {
1080 foreach ($relationValue as $ltype => $val) {
1081 // If the location name has a space in it the we need to handle that. This
1082 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1083 // improve it should be secure in the knowled it will be caught.
1084 $ltype = str_replace(' ', '_', $ltype);
1085 foreach (array_keys($val) as $fld) {
1086 $type = explode('-', $fld);
1087 $fldValue = "{$ltype}-" . $type[0];
1088 if (!empty($type[1])) {
1089 $fldValue .= "-" . $type[1];
1091 // CRM-3157: localise country, region (both have ‘country’ context)
1092 // and state_province (‘province’ context)
1094 case (!is_object($relDAO)):
1095 $row[$field . '_' . $fldValue] = '';
1098 case in_array('country', $type):
1099 case in_array('world_region', $type):
1100 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1101 ['context' => 'country']
1105 case in_array('state_province', $type):
1106 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1107 ['context' => 'province']
1112 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1118 elseif (isset($fieldValue) && $fieldValue != '') {
1119 //check for custom data
1120 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1121 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1124 //normal relationship fields
1125 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1126 switch ($relationField) {
1128 case 'world_region':
1129 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1132 case 'state_province':
1133 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1137 $row[$relPrefix] = $fieldValue;
1143 // if relation field is empty or null
1144 $row[$relPrefix] = '';
1150 * Get the ids that we want to get related contact details for.
1153 * @param int $exportMode
1157 protected static function getIDsForRelatedContact($ids, $exportMode) {
1158 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1161 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1163 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1164 $dao = CRM_Core_DAO
::executeQuery("
1165 SELECT contact_id FROM civicrm_activity_contact
1166 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1167 record_type_id = {$sourceID}
1170 while ($dao->fetch()) {
1171 $relIDs[] = $dao->contact_id
;
1175 $component = self
::exportComponent($exportMode);
1177 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1178 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1181 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1188 * @param \CRM_Export_BAO_ExportProcessor $processor
1189 * @param $componentTable
1191 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1192 $allRelContactArray = $relationQuery = [];
1193 $queryMode = $processor->getQueryMode();
1194 $exportMode = $processor->getExportMode();
1196 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1197 $allRelContactArray[$relationshipKey] = [];
1198 // build Query for each relationship
1199 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1200 NULL, FALSE, FALSE, $queryMode
1202 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1204 list($id, $direction) = explode('_', $relationshipKey, 2);
1205 // identify the relationship direction
1206 $contactA = 'contact_id_a';
1207 $contactB = 'contact_id_b';
1208 if ($direction == 'b_a') {
1209 $contactA = 'contact_id_b';
1210 $contactB = 'contact_id_a';
1212 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1214 $relationshipJoin = $relationshipClause = '';
1215 if (!$selectAll && $componentTable) {
1216 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1218 elseif (!empty($relIDs)) {
1219 $relID = implode(',', $relIDs);
1220 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1223 $relationFrom = " {$relationFrom}
1224 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1225 {$relationshipJoin} ";
1227 //check for active relationship status only
1228 $today = date('Ymd');
1229 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1230 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1231 CRM_Core_DAO
::disableFullGroupByMode();
1232 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1233 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1235 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1236 CRM_Core_DAO
::reenableFullGroupByMode();
1238 while ($allRelContactDAO->fetch()) {
1239 $relationQuery->convertToPseudoNames($allRelContactDAO);
1241 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1242 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1243 foreach (array_keys($relationReturnProperties) as $property) {
1244 if ($property === 'location') {
1245 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1246 // $processor->setRelationshipValue from fetchRelationshipDetails
1247 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1248 foreach (array_keys($locationValues) as $locationValue) {
1249 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1250 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1255 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);