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 default return property for export based on mode
47 * @param int $exportMode
51 * Default Return property
53 public static function defaultReturnProperty($exportMode) {
54 // hack to add default return property based on export mode
56 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
57 $property = 'contribution_id';
59 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
60 $property = 'participant_id';
62 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
63 $property = 'membership_id';
65 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
66 $property = 'pledge_id';
68 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
69 $property = 'case_id';
71 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
72 $property = 'grant_id';
74 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
75 $property = 'activity_id';
81 * Get Export component
83 * @param int $exportMode
87 * CiviCRM Export Component
89 public static function exportComponent($exportMode) {
90 switch ($exportMode) {
91 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
92 $component = 'civicrm_contribution';
95 case CRM_Export_Form_Select
::EVENT_EXPORT
:
96 $component = 'civicrm_participant';
99 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
100 $component = 'civicrm_membership';
103 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
104 $component = 'civicrm_pledge';
107 case CRM_Export_Form_Select
::GRANT_EXPORT
:
108 $component = 'civicrm_grant';
115 * Get Query Group By Clause
116 * @param \CRM_Export_BAO_ExportProcessor $processor
118 * @param array $returnProperties
120 * @param object $query
121 * CRM_Contact_BAO_Query
126 public static function getGroupBy($processor, $returnProperties, $query) {
128 $exportMode = $processor->getExportMode();
129 $queryMode = $processor->getQueryMode();
130 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
131 CRM_Utils_Array
::value('notes', $returnProperties) ||
133 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
135 $groupBy = "contact_a.id";
138 switch ($exportMode) {
139 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
140 $groupBy = 'civicrm_contribution.id';
141 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
142 // especial group by when soft credit columns are included
143 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
147 case CRM_Export_Form_Select
::EVENT_EXPORT
:
148 $groupBy = 'civicrm_participant.id';
151 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
152 $groupBy = "civicrm_membership.id";
156 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
157 $groupBy = "civicrm_activity.id ";
160 return $groupBy ?
' GROUP BY ' . implode(', ', (array) $groupBy) : '';
164 * Get the list the export fields.
166 * @param int $selectAll
167 * User preference while export.
170 * @param array $params
171 * Associated array of fields.
172 * @param string $order
174 * @param array $fields
175 * Associated array of fields.
176 * @param array $moreReturnProperties
177 * Additional return fields.
178 * @param int $exportMode
180 * @param string $componentClause
182 * @param string $componentTable
184 * @param bool $mergeSameAddress
185 * Merge records if they have same address.
186 * @param bool $mergeSameHousehold
187 * Merge records if they belong to the same household.
189 * @param array $exportParams
190 * @param string $queryOperator
193 * An array can be requested from within a unit test.
195 * @throws \CRM_Core_Exception
197 public static function exportComponents(
203 $moreReturnProperties = NULL,
204 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
205 $componentClause = NULL,
206 $componentTable = NULL,
207 $mergeSameAddress = FALSE,
208 $mergeSameHousehold = FALSE,
210 $queryOperator = 'AND'
214 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
215 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
218 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly);
219 $returnProperties = [];
222 foreach ($fields as $key => $value) {
223 $fieldName = CRM_Utils_Array
::value(1, $value);
224 if (!$fieldName ||
$processor->isHouseholdMergeRelationshipTypeKey($fieldName)) {
228 if ($processor->isRelationshipTypeKey($fieldName) && (!empty($value[2]) ||
!empty($value[4]))) {
229 $returnProperties[$fieldName] = $processor->setRelationshipReturnProperties($value, $fieldName);
231 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
232 $locationName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $value[2]);
233 if ($fieldName == 'phone') {
234 $returnProperties['location'][$locationName]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
236 elseif ($fieldName == 'im') {
237 $returnProperties['location'][$locationName]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
240 $returnProperties['location'][$locationName][$fieldName] = 1;
244 //hack to fix component fields
245 //revert mix of event_id and title
246 if ($fieldName == 'event_id') {
247 $returnProperties['event_id'] = 1;
250 $returnProperties[$fieldName] = 1;
254 $defaultExportMode = self
::defaultReturnProperty($exportMode);
255 if ($defaultExportMode) {
256 $returnProperties[$defaultExportMode] = 1;
260 $returnProperties = $processor->getDefaultReturnProperties();
262 // @todo - we are working towards this being entirely a property of the processor
263 $processor->setReturnProperties($returnProperties);
264 $paymentTableId = $processor->getPaymentTableID();
266 if ($mergeSameAddress) {
267 //make sure the addressee fields are selected
268 //while using merge same address feature
269 $returnProperties['addressee'] = 1;
270 $returnProperties['postal_greeting'] = 1;
271 $returnProperties['email_greeting'] = 1;
272 $returnProperties['street_name'] = 1;
273 $returnProperties['household_name'] = 1;
274 $returnProperties['street_address'] = 1;
275 $returnProperties['city'] = 1;
276 $returnProperties['state_province'] = 1;
278 // some columns are required for assistance incase they are not already present
279 $exportParams['merge_same_address']['temp_columns'] = [];
280 $tempColumns = ['id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id'];
281 foreach ($tempColumns as $column) {
282 if (!array_key_exists($column, $returnProperties)) {
283 $returnProperties[$column] = 1;
284 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
285 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
290 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
291 // If an Additional Group is selected, then all contacts in that group are
292 // added to the export set (filtering out duplicates).
294 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";
295 CRM_Core_DAO
::executeQuery($query);
298 if ($moreReturnProperties) {
300 if (!empty($moreReturnProperties['group'])) {
301 unset($moreReturnProperties['group']);
302 $moreReturnProperties['groups'] = 1;
304 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
307 $exportParams['postal_mailing_export']['temp_columns'] = [];
308 if ($exportParams['exportOption'] == 2 &&
309 isset($exportParams['postal_mailing_export']) &&
310 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
312 $postalColumns = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
313 foreach ($postalColumns as $column) {
314 if (!array_key_exists($column, $returnProperties)) {
315 $returnProperties[$column] = 1;
316 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
321 // rectify params to what proximity search expects if there is a value for prox_distance
323 if (!empty($params)) {
324 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
327 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
329 if ($mergeSameHousehold == 1) {
330 if (empty($returnProperties['id'])) {
331 $returnProperties['id'] = 1;
334 $processor->setHouseholdMergeReturnProperties(array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1)));
337 // This perhaps only needs calling when $mergeSameHousehold == 1
338 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
340 // make sure the groups stuff is included only if specifically specified
341 // by the fields param (CRM-1969), else we limit the contacts outputted to only
342 // ones that are part of a group
343 if (!empty($returnProperties['groups'])) {
344 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
345 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
346 // total hack for export, CRM-3618
347 $from = str_replace($oldClause,
353 if (!$selectAll && $componentTable) {
354 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
356 elseif ($componentClause) {
358 $where = "WHERE $componentClause";
361 $where .= " AND $componentClause";
365 // CRM-13982 - check if is deleted
366 $excludeTrashed = TRUE;
367 foreach ($params as $value) {
368 if ($value[0] == 'contact_is_deleted') {
369 $excludeTrashed = FALSE;
372 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
375 $where = "WHERE $trashClause";
378 $where .= " AND $trashClause";
381 $queryString = "$select $from $where $having";
383 $groupBy = self
::getGroupBy($processor, $returnProperties, $query);
385 $queryString .= $groupBy;
388 // always add contact_a.id to the ORDER clause
389 // so the order is deterministic
391 if (strpos('contact_a.id', $order) === FALSE) {
392 $order .= ", contact_a.id";
395 list($field, $dir) = explode(' ', $order, 2);
396 $field = trim($field);
397 if (!empty($returnProperties[$field])) {
399 $queryString .= " ORDER BY $order";
403 $addPaymentHeader = FALSE;
405 list($outputColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
407 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
408 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
409 // test exists covering this...
410 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
411 $processor->setColumnAsCalculationOnly($field);
415 $paymentDetails = [];
416 if ($processor->isExportPaymentFields()) {
417 // get payment related in for event and members
418 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
419 //get all payment headers.
420 // If we haven't selected specific payment fields, load in all the
422 if (!$processor->isExportSpecifiedPaymentFields()) {
423 if (!empty($paymentDetails)) {
424 $addPaymentHeader = TRUE;
425 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
426 $processor->addOutputSpecification($paymentField);
432 $componentDetails = [];
434 $rowCount = self
::EXPORT_ROW_COUNT
;
436 // we write to temp table often to avoid using too much memory
441 $headerRows = $processor->getHeaderRows();
442 $sqlColumns = $processor->getSQLColumns();
443 $exportTempTable = self
::createTempTable($sqlColumns);
444 $limitReached = FALSE;
446 while (!$limitReached) {
447 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
448 CRM_Core_DAO
::disableFullGroupByMode();
449 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
450 CRM_Core_DAO
::reenableFullGroupByMode();
451 // If this is less than our limit by the end of the iteration we do not need to run the query again to
452 // check if some remain.
453 $rowsThisIteration = 0;
455 while ($iterationDAO->fetch()) {
457 $rowsThisIteration++
;
458 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
459 if ($row === FALSE) {
463 // add component info
464 // write the row to a file
465 $componentDetails[] = $row;
467 // output every $tempRowCount rows
468 if ($count %
$tempRowCount == 0) {
469 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
470 $componentDetails = [];
473 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
474 $limitReached = TRUE;
476 $offset +
= $rowCount;
479 if ($exportTempTable) {
480 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
482 // do merge same address and merge same household processing
483 if ($mergeSameAddress) {
484 self
::mergeSameAddress($exportTempTable, $sqlColumns, $exportParams);
488 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
490 // In order to be able to write a unit test against this function we need to suppress
491 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
492 if (empty($exportParams['suppress_csv_for_testing'])) {
493 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor);
496 // return tableName sqlColumns headerRows in test context
497 return [$exportTempTable, $sqlColumns, $headerRows, $processor];
500 // delete the export temp table and component table
501 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
502 CRM_Core_DAO
::executeQuery($sql);
503 CRM_Core_DAO
::reenableFullGroupByMode();
504 CRM_Utils_System
::civiExit();
507 CRM_Core_DAO
::reenableFullGroupByMode();
508 throw new CRM_Core_Exception(ts('No records to export'));
513 * Handle import error file creation.
515 public static function invoke() {
516 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
517 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
518 if (empty($parserName) ||
empty($type)) {
522 // clean and ensure parserName is a valid string
523 $parserName = CRM_Utils_String
::munge($parserName);
524 $parserClass = explode('_', $parserName);
526 // make sure parserClass is in the CRM namespace and
527 // at least 3 levels deep
528 if ($parserClass[0] == 'CRM' &&
529 count($parserClass) >= 3
531 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
532 // ensure the functions exists
533 if (method_exists($parserName, 'errorFileName') &&
534 method_exists($parserName, 'saveFileName')
536 $errorFileName = $parserName::errorFileName($type);
537 $saveFileName = $parserName::saveFileName($type);
538 if (!empty($errorFileName) && !empty($saveFileName)) {
539 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
540 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
541 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
542 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
543 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
545 readfile($errorFileName);
549 CRM_Utils_System
::civiExit();
553 * @param $customSearchClass
557 public static function exportCustom($customSearchClass, $formValues, $order) {
558 $ext = CRM_Extension_System
::singleton()->getMapper();
559 if (!$ext->isExtensionClass($customSearchClass)) {
560 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
563 require_once $ext->classToPath($customSearchClass);
565 $search = new $customSearchClass($formValues);
567 $includeContactIDs = FALSE;
568 if ($formValues['radio_ts'] == 'ts_sel') {
569 $includeContactIDs = TRUE;
572 $sql = $search->all(0, 0, $order, $includeContactIDs);
574 $columns = $search->columns();
576 $header = array_keys($columns);
577 $fields = array_values($columns);
580 $dao = CRM_Core_DAO
::executeQuery($sql);
582 if (method_exists($search, 'alterRow')) {
585 while ($dao->fetch()) {
588 foreach ($fields as $field) {
589 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
590 $row[$field] = $dao->$unqualified_field;
593 $search->alterRow($row);
598 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
599 CRM_Utils_System
::civiExit();
603 * @param string $tableName
607 public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
608 if (empty($details)) {
617 $id = CRM_Core_DAO
::singleValueQuery($sql);
624 foreach ($details as $row) {
626 $valueString = [$id];
627 foreach ($row as $value) {
629 $valueString[] = "''";
632 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
635 $sqlClause[] = '(' . implode(',', $valueString) . ')';
637 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
638 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
640 $sqlValueString = implode(",\n", $sqlClause);
643 INSERT INTO $tableName $sqlColumnString
644 VALUES $sqlValueString
646 CRM_Core_DAO
::executeQuery($sql);
654 public static function createTempTable($sqlColumns) {
655 //creating a temporary table for the search result that need be exported
656 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
658 // also create the sql table
659 $exportTempTable->drop();
661 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
662 if (!empty($sqlColumns)) {
663 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
666 $sql .= "\n PRIMARY KEY ( id )";
668 // add indexes for street_address and household_name if present
672 'civicrm_primary_id',
675 foreach ($addIndices as $index) {
676 if (isset($sqlColumns[$index])) {
678 INDEX index_{$index}( $index )
683 $exportTempTable->createWithColumns($sql);
684 return $exportTempTable->getName();
688 * @param string $tableName
690 * @param array $exportParams
692 public static function mergeSameAddress($tableName, &$sqlColumns, $exportParams) {
693 // check if any records are present based on if they have used shared address feature,
694 // and not based on if city / state .. matches.
696 SELECT r1.id as copy_id,
697 r1.civicrm_primary_id as copy_contact_id,
698 r1.addressee as copy_addressee,
699 r1.addressee_id as copy_addressee_id,
700 r1.postal_greeting as copy_postal_greeting,
701 r1.postal_greeting_id as copy_postal_greeting_id,
703 r2.civicrm_primary_id as master_contact_id,
704 r2.postal_greeting as master_postal_greeting,
705 r2.postal_greeting_id as master_postal_greeting_id,
706 r2.addressee as master_addressee,
707 r2.addressee_id as master_addressee_id
709 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
710 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
712 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
714 // find all the records that have the same street address BUT not in a household
715 // require match on city and state as well
717 SELECT r1.id as master_id,
718 r1.civicrm_primary_id as master_contact_id,
719 r1.postal_greeting as master_postal_greeting,
720 r1.postal_greeting_id as master_postal_greeting_id,
721 r1.addressee as master_addressee,
722 r1.addressee_id as master_addressee_id,
724 r2.civicrm_primary_id as copy_contact_id,
725 r2.postal_greeting as copy_postal_greeting,
726 r2.postal_greeting_id as copy_postal_greeting_id,
727 r2.addressee as copy_addressee,
728 r2.addressee_id as copy_addressee_id
730 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
731 r1.city = r2.city AND
732 r1.state_province_id = r2.state_province_id )
733 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
734 AND ( r2.household_name IS NULL OR r2.household_name = '' )
735 AND ( r1.street_address != '' )
739 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
741 // unset ids from $merge already present in $linkedMerge
742 foreach ($linkedMerge as $masterID => $values) {
744 $keys = array_merge($keys, array_keys($values['copy']));
745 foreach ($merge as $mid => $vals) {
746 if (in_array($mid, $keys)) {
750 foreach ($values['copy'] as $copyId) {
751 if (in_array($copyId, $keys)) {
752 unset($merge[$mid]['copy'][$copyId]);
758 $merge = $merge +
$linkedMerge;
760 foreach ($merge as $masterID => $values) {
763 SET addressee = %1, postal_greeting = %2, email_greeting = %3
767 1 => [$values['addressee'], 'String'],
768 2 => [$values['postalGreeting'], 'String'],
769 3 => [$values['emailGreeting'], 'String'],
770 4 => [$masterID, 'Integer'],
772 CRM_Core_DAO
::executeQuery($sql, $params);
775 $deleteIDs = array_keys($values['copy']);
776 $deleteIDString = implode(',', $deleteIDs);
778 DELETE FROM $tableName
779 WHERE id IN ( $deleteIDString )
781 CRM_Core_DAO
::executeQuery($sql);
784 // unset temporary columns that were added for postal mailing format
785 // @todo - this part is pretty close to ready to be removed....
786 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
787 $unsetKeys = array_keys($sqlColumns);
788 foreach ($unsetKeys as $headerKey => $sqlColKey) {
789 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
790 unset($sqlColumns[$sqlColKey]);
797 * @param int $contactId
798 * @param array $exportParams
802 public static function _replaceMergeTokens($contactId, $exportParams) {
810 foreach ($greetingFields as $greeting) {
811 if (!empty($exportParams[$greeting])) {
812 $greetingLabel = $exportParams[$greeting];
813 if (empty($contact)) {
818 $contact = civicrm_api('contact', 'get', $values);
820 if (!empty($contact['is_error'])) {
823 $contact = $contact['values'][$contact['id']];
826 $tokens = ['contact' => $greetingLabel];
827 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
834 * The function unsets static part of the string, if token is the dynamic part.
836 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
837 * i.e 'Hello Alan' => converted to => 'Alan'
839 * @param string $parsedString
840 * @param string $defaultGreeting
841 * @param bool $addressMergeGreetings
842 * @param string $greetingType
846 public static function _trimNonTokens(
847 &$parsedString, $defaultGreeting,
848 $addressMergeGreetings, $greetingType = 'postal_greeting'
850 if (!empty($addressMergeGreetings[$greetingType])) {
851 $greetingLabel = $addressMergeGreetings[$greetingType];
853 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
855 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
856 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
857 foreach ($stringsToBeReplaced as $key => $string) {
859 $stringsToBeReplaced[$key] = ltrim($string);
861 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
863 return $parsedString;
868 * @param array $exportParams
869 * @param bool $sharedAddress
873 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
874 static $contactGreetingTokens = [];
876 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
877 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
879 $merge = $parents = [];
880 $dao = CRM_Core_DAO
::executeQuery($sql);
882 while ($dao->fetch()) {
883 $masterID = $dao->master_id
;
884 $copyID = $dao->copy_id
;
885 $masterPostalGreeting = $dao->master_postal_greeting
;
886 $masterAddressee = $dao->master_addressee
;
887 $copyAddressee = $dao->copy_addressee
;
889 if (!$sharedAddress) {
890 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
891 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
893 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
894 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
896 $masterAddressee = CRM_Utils_Array
::value('addressee',
897 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
900 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
901 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
903 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
904 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
906 $copyAddressee = CRM_Utils_Array
::value('addressee',
907 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
911 if (!isset($merge[$masterID])) {
912 // check if this is an intermediate child
913 // this happens if there are 3 or more matches a,b, c
914 // the above query will return a, b / a, c / b, c
915 // we might be doing a bit more work, but for now its ok, unless someone
916 // knows how to fix the query above
917 if (isset($parents[$masterID])) {
918 $masterID = $parents[$masterID];
921 $merge[$masterID] = [
922 'addressee' => $masterAddressee,
924 'postalGreeting' => $masterPostalGreeting,
926 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
929 $parents[$copyID] = $masterID;
931 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
933 if (!empty($exportParams['postal_greeting_other']) &&
934 count($merge[$masterID]['copy']) >= 1
936 // use static greetings specified if no of contacts > 2
937 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
939 elseif ($copyPostalGreeting) {
940 self
::_trimNonTokens($copyPostalGreeting,
941 $postalOptions[$dao->copy_postal_greeting_id
],
944 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
945 // if there happens to be a duplicate, remove it
946 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
949 if (!empty($exportParams['addressee_other']) &&
950 count($merge[$masterID]['copy']) >= 1
952 // use static greetings specified if no of contacts > 2
953 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
955 elseif ($copyAddressee) {
956 self
::_trimNonTokens($copyAddressee,
957 $addresseeOptions[$dao->copy_addressee_id
],
958 $exportParams, 'addressee'
960 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
963 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
970 * @param $exportTempTable
973 * @param \CRM_Export_BAO_ExportProcessor $processor
975 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor) {
976 $exportMode = $processor->getExportMode();
979 $limit = self
::EXPORT_ROW_COUNT
;
981 $query = "SELECT * FROM $exportTempTable";
984 $limitQuery = $query . "
985 LIMIT $offset, $limit
987 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
993 $componentDetails = [];
994 while ($dao->fetch()) {
997 foreach ($sqlColumns as $column => $dontCare) {
998 $row[$column] = $dao->$column;
1000 $componentDetails[] = $row;
1002 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
1009 $writeHeader = FALSE;
1015 * Build componentPayment fields.
1017 * This is no longer used by export but BAO_Mapping still calls it & we
1018 * should find a generic way to handle this or move this to that class.
1022 public static function componentPaymentFields() {
1023 static $componentPaymentFields;
1024 if (!isset($componentPaymentFields)) {
1025 $componentPaymentFields = [
1026 'componentPaymentField_total_amount' => ts('Total Amount'),
1027 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1028 'componentPaymentField_received_date' => ts('Date Received'),
1029 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1030 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1033 return $componentPaymentFields;
1037 * Get the various arrays that we use to structure our output.
1039 * The extraction of these has been moved to a separate function for clarity and so that
1040 * tests can be added - in particular on the $outputHeaders array.
1042 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1043 * as a step on the refactoring path rather than how it should be.
1045 * @param array $returnProperties
1046 * @param \CRM_Export_BAO_ExportProcessor $processor
1049 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1050 * alias for the field generated by BAO_Query object.
1051 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1052 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1053 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1054 * I'm too embarassed to discuss here.
1056 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1057 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1058 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1059 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1060 * - a) the function used is more efficient or
1061 * - b) this code is old & outdated. Submit your answers to circular bin or better
1062 * yet find a way to comment them for posterity.
1064 public static function getExportStructureArrays($returnProperties, $processor) {
1065 $outputColumns = $metadata = [];
1066 $queryFields = $processor->getQueryFields();
1067 foreach ($returnProperties as $key => $value) {
1068 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
1069 $outputColumns[$key] = $value;
1070 $processor->addOutputSpecification($key);
1072 elseif ($processor->isRelationshipTypeKey($key)) {
1073 $outputColumns[$key] = $value;
1074 foreach ($value as $relationField => $relationValue) {
1075 // below block is same as primary block (duplicate)
1076 if (isset($queryFields[$relationField]['title'])) {
1077 $processor->addOutputSpecification($relationField, $key);
1079 elseif (is_array($relationValue) && $relationField == 'location') {
1080 // fix header for location type case
1081 foreach ($relationValue as $ltype => $val) {
1082 foreach (array_keys($val) as $fld) {
1083 $type = explode('-', $fld);
1084 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
1091 foreach ($value as $locationType => $locationFields) {
1092 foreach (array_keys($locationFields) as $locationFieldName) {
1093 $type = explode('-', $locationFieldName);
1095 $actualDBFieldName = $type[0];
1096 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1098 if (!empty($type[1])) {
1099 $daoFieldName .= "-" . $type[1];
1101 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
1102 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
1103 $outputColumns[$daoFieldName] = TRUE;
1108 return [$outputColumns, $metadata];
1112 * Get the values of linked household contact.
1114 * @param CRM_Core_DAO $relDAO
1115 * @param array $value
1116 * @param string $field
1119 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1120 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1121 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1122 $i18n = CRM_Core_I18n
::singleton();
1123 $field = $field . '_';
1125 foreach ($value as $relationField => $relationValue) {
1126 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1127 $fieldValue = $relDAO->$relationField;
1128 if ($relationField == 'phone_type_id') {
1129 $fieldValue = $phoneTypes[$relationValue];
1131 elseif ($relationField == 'provider_id') {
1132 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1135 elseif (is_object($relDAO) && in_array($relationField, [
1140 //special case for greeting replacement
1141 $fldValue = "{$relationField}_display";
1142 $fieldValue = $relDAO->$fldValue;
1145 elseif (is_object($relDAO) && $relationField == 'state_province') {
1146 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1148 elseif (is_object($relDAO) && $relationField == 'country') {
1149 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1154 $relPrefix = $field . $relationField;
1156 if (is_object($relDAO) && $relationField == 'id') {
1157 $row[$relPrefix] = $relDAO->contact_id
;
1159 elseif (is_array($relationValue) && $relationField == 'location') {
1160 foreach ($relationValue as $ltype => $val) {
1161 // If the location name has a space in it the we need to handle that. This
1162 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1163 // improve it should be secure in the knowled it will be caught.
1164 $ltype = str_replace(' ', '_', $ltype);
1165 foreach (array_keys($val) as $fld) {
1166 $type = explode('-', $fld);
1167 $fldValue = "{$ltype}-" . $type[0];
1168 if (!empty($type[1])) {
1169 $fldValue .= "-" . $type[1];
1171 // CRM-3157: localise country, region (both have ‘country’ context)
1172 // and state_province (‘province’ context)
1174 case (!is_object($relDAO)):
1175 $row[$field . '_' . $fldValue] = '';
1178 case in_array('country', $type):
1179 case in_array('world_region', $type):
1180 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1181 ['context' => 'country']
1185 case in_array('state_province', $type):
1186 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1187 ['context' => 'province']
1192 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1198 elseif (isset($fieldValue) && $fieldValue != '') {
1199 //check for custom data
1200 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1201 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1204 //normal relationship fields
1205 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1206 switch ($relationField) {
1208 case 'world_region':
1209 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1212 case 'state_province':
1213 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1217 $row[$relPrefix] = $fieldValue;
1223 // if relation field is empty or null
1224 $row[$relPrefix] = '';
1230 * Get the ids that we want to get related contact details for.
1233 * @param int $exportMode
1237 protected static function getIDsForRelatedContact($ids, $exportMode) {
1238 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1241 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1243 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1244 $dao = CRM_Core_DAO
::executeQuery("
1245 SELECT contact_id FROM civicrm_activity_contact
1246 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1247 record_type_id = {$sourceID}
1250 while ($dao->fetch()) {
1251 $relIDs[] = $dao->contact_id
;
1255 $component = self
::exportComponent($exportMode);
1257 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1258 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1261 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1268 * @param \CRM_Export_BAO_ExportProcessor $processor
1269 * @param $componentTable
1271 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1272 $allRelContactArray = $relationQuery = [];
1273 $queryMode = $processor->getQueryMode();
1274 $exportMode = $processor->getExportMode();
1276 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1277 $allRelContactArray[$relationshipKey] = [];
1278 // build Query for each relationship
1279 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1280 NULL, FALSE, FALSE, $queryMode
1282 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1284 list($id, $direction) = explode('_', $relationshipKey, 2);
1285 // identify the relationship direction
1286 $contactA = 'contact_id_a';
1287 $contactB = 'contact_id_b';
1288 if ($direction == 'b_a') {
1289 $contactA = 'contact_id_b';
1290 $contactB = 'contact_id_a';
1292 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1294 $relationshipJoin = $relationshipClause = '';
1295 if (!$selectAll && $componentTable) {
1296 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1298 elseif (!empty($relIDs)) {
1299 $relID = implode(',', $relIDs);
1300 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1303 $relationFrom = " {$relationFrom}
1304 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1305 {$relationshipJoin} ";
1307 //check for active relationship status only
1308 $today = date('Ymd');
1309 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1310 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1311 CRM_Core_DAO
::disableFullGroupByMode();
1312 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1313 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1315 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1316 CRM_Core_DAO
::reenableFullGroupByMode();
1318 while ($allRelContactDAO->fetch()) {
1319 $relationQuery->convertToPseudoNames($allRelContactDAO);
1321 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1322 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1323 foreach (array_keys($relationReturnProperties) as $property) {
1324 if ($property === 'location') {
1325 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1326 // $processor->setRelationshipValue from fetchRelationshipDetails
1327 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1328 foreach (array_keys($locationValues) as $locationValue) {
1329 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1330 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1335 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);