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 $exportParams['postal_mailing_export']['temp_columns'] = [];
228 if ($exportParams['exportOption'] == 2 &&
229 isset($exportParams['postal_mailing_export']) &&
230 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
232 $postalColumns = ['is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1'];
233 foreach ($postalColumns as $column) {
234 if (!array_key_exists($column, $returnProperties)) {
235 $returnProperties[$column] = 1;
236 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
241 // rectify params to what proximity search expects if there is a value for prox_distance
243 if (!empty($params)) {
244 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
247 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
249 if ($mergeSameHousehold == 1) {
250 if (empty($returnProperties['id'])) {
251 $returnProperties['id'] = 1;
254 $processor->setHouseholdMergeReturnProperties(array_diff_key($returnProperties, array_fill_keys(['location_type', 'im_provider'], 1)));
257 // This perhaps only needs calling when $mergeSameHousehold == 1
258 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
260 // make sure the groups stuff is included only if specifically specified
261 // by the fields param (CRM-1969), else we limit the contacts outputted to only
262 // ones that are part of a group
263 if (!empty($returnProperties['groups'])) {
264 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
265 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
266 // total hack for export, CRM-3618
267 $from = str_replace($oldClause,
273 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
274 if (!$selectAll && $componentTable) {
275 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
277 elseif ($componentClause) {
278 $whereClauses[] = $componentClause;
281 // CRM-13982 - check if is deleted
282 foreach ($params as $value) {
283 if ($value[0] == 'contact_is_deleted') {
284 unset($whereClauses['trash_clause']);
289 $where = "WHERE " . implode(' AND ', $whereClauses);
292 $where .= " AND " . implode(' AND ', $whereClauses);
295 $queryString = "$select $from $where $having";
297 $groupBy = self
::getGroupBy($processor, $returnProperties, $query);
299 $queryString .= $groupBy;
302 // always add contact_a.id to the ORDER clause
303 // so the order is deterministic
305 if (strpos('contact_a.id', $order) === FALSE) {
306 $order .= ", contact_a.id";
309 list($field, $dir) = explode(' ', $order, 2);
310 $field = trim($field);
311 if (!empty($returnProperties[$field])) {
313 $queryString .= " ORDER BY $order";
317 $addPaymentHeader = FALSE;
319 list($outputColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
321 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
322 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
323 // test exists covering this...
324 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
325 $processor->setColumnAsCalculationOnly($field);
329 $paymentDetails = [];
330 if ($processor->isExportPaymentFields()) {
331 // get payment related in for event and members
332 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
333 //get all payment headers.
334 // If we haven't selected specific payment fields, load in all the
336 if (!$processor->isExportSpecifiedPaymentFields()) {
337 if (!empty($paymentDetails)) {
338 $addPaymentHeader = TRUE;
339 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
340 $processor->addOutputSpecification($paymentField);
346 $componentDetails = [];
348 $rowCount = self
::EXPORT_ROW_COUNT
;
350 // we write to temp table often to avoid using too much memory
355 $headerRows = $processor->getHeaderRows();
356 $sqlColumns = $processor->getSQLColumns();
357 $processor->setTemporaryTable(self
::createTempTable($sqlColumns));
358 $limitReached = FALSE;
360 while (!$limitReached) {
361 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
362 CRM_Core_DAO
::disableFullGroupByMode();
363 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
364 CRM_Core_DAO
::reenableFullGroupByMode();
365 // If this is less than our limit by the end of the iteration we do not need to run the query again to
366 // check if some remain.
367 $rowsThisIteration = 0;
369 while ($iterationDAO->fetch()) {
371 $rowsThisIteration++
;
372 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $paymentTableId);
373 if ($row === FALSE) {
377 // add component info
378 // write the row to a file
379 $componentDetails[] = $row;
381 // output every $tempRowCount rows
382 if ($count %
$tempRowCount == 0) {
383 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
384 $componentDetails = [];
387 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
388 $limitReached = TRUE;
390 $offset +
= $rowCount;
393 if ($processor->getTemporaryTable()) {
394 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
396 // do merge same address and merge same household processing
397 if ($mergeSameAddress) {
398 self
::mergeSameAddress($processor, $sqlColumns, $exportParams);
402 $table = $processor->getTemporaryTable();
403 CRM_Utils_Hook
::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
404 if ($table !== $processor->getTemporaryTable()) {
405 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
406 $processor->setTemporaryTable($table);
409 // In order to be able to write a unit test against this function we need to suppress
410 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
411 if (empty($exportParams['suppress_csv_for_testing'])) {
412 self
::writeCSVFromTable($headerRows, $sqlColumns, $processor);
415 // return tableName sqlColumns headerRows in test context
416 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
419 // delete the export temp table and component table
420 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
421 CRM_Core_DAO
::executeQuery($sql);
422 CRM_Core_DAO
::reenableFullGroupByMode();
423 CRM_Utils_System
::civiExit(0, ['processor' => $processor]);
426 CRM_Core_DAO
::reenableFullGroupByMode();
427 throw new CRM_Core_Exception(ts('No records to export'));
432 * Handle import error file creation.
434 public static function invoke() {
435 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
436 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
437 if (empty($parserName) ||
empty($type)) {
441 // clean and ensure parserName is a valid string
442 $parserName = CRM_Utils_String
::munge($parserName);
443 $parserClass = explode('_', $parserName);
445 // make sure parserClass is in the CRM namespace and
446 // at least 3 levels deep
447 if ($parserClass[0] == 'CRM' &&
448 count($parserClass) >= 3
450 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
451 // ensure the functions exists
452 if (method_exists($parserName, 'errorFileName') &&
453 method_exists($parserName, 'saveFileName')
455 $errorFileName = $parserName::errorFileName($type);
456 $saveFileName = $parserName::saveFileName($type);
457 if (!empty($errorFileName) && !empty($saveFileName)) {
458 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
459 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
460 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
461 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
462 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
464 readfile($errorFileName);
468 CRM_Utils_System
::civiExit();
472 * @param $customSearchClass
476 public static function exportCustom($customSearchClass, $formValues, $order) {
477 $ext = CRM_Extension_System
::singleton()->getMapper();
478 if (!$ext->isExtensionClass($customSearchClass)) {
479 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
482 require_once $ext->classToPath($customSearchClass);
484 $search = new $customSearchClass($formValues);
486 $includeContactIDs = FALSE;
487 if ($formValues['radio_ts'] == 'ts_sel') {
488 $includeContactIDs = TRUE;
491 $sql = $search->all(0, 0, $order, $includeContactIDs);
493 $columns = $search->columns();
495 $header = array_keys($columns);
496 $fields = array_values($columns);
499 $dao = CRM_Core_DAO
::executeQuery($sql);
501 if (method_exists($search, 'alterRow')) {
504 while ($dao->fetch()) {
507 foreach ($fields as $field) {
508 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
509 $row[$field] = $dao->$unqualified_field;
512 $search->alterRow($row);
517 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
518 CRM_Utils_System
::civiExit();
522 * @param \CRM_Export_BAO_ExportProcessor $processor
526 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
527 $tableName = $processor->getTemporaryTable();
528 if (empty($details)) {
537 $id = CRM_Core_DAO
::singleValueQuery($sql);
544 foreach ($details as $row) {
546 $valueString = [$id];
547 foreach ($row as $value) {
549 $valueString[] = "''";
552 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
555 $sqlClause[] = '(' . implode(',', $valueString) . ')';
557 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
558 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
560 $sqlValueString = implode(",\n", $sqlClause);
563 INSERT INTO $tableName $sqlColumnString
564 VALUES $sqlValueString
566 CRM_Core_DAO
::executeQuery($sql);
574 public static function createTempTable($sqlColumns) {
575 //creating a temporary table for the search result that need be exported
576 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export');
578 // also create the sql table
579 $exportTempTable->drop();
581 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
582 if (!empty($sqlColumns)) {
583 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
586 $sql .= "\n PRIMARY KEY ( id )";
588 // add indexes for street_address and household_name if present
592 'civicrm_primary_id',
595 foreach ($addIndices as $index) {
596 if (isset($sqlColumns[$index])) {
598 INDEX index_{$index}( $index )
603 $exportTempTable->createWithColumns($sql);
604 return $exportTempTable->getName();
608 * @param \CRM_Export_BAO_ExportProcessor $processor
610 * @param array $exportParams
612 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
613 $tableName = $processor->getTemporaryTable();
614 // check if any records are present based on if they have used shared address feature,
615 // and not based on if city / state .. matches.
617 SELECT r1.id as copy_id,
618 r1.civicrm_primary_id as copy_contact_id,
619 r1.addressee as copy_addressee,
620 r1.addressee_id as copy_addressee_id,
621 r1.postal_greeting as copy_postal_greeting,
622 r1.postal_greeting_id as copy_postal_greeting_id,
624 r2.civicrm_primary_id as master_contact_id,
625 r2.postal_greeting as master_postal_greeting,
626 r2.postal_greeting_id as master_postal_greeting_id,
627 r2.addressee as master_addressee,
628 r2.addressee_id as master_addressee_id
630 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
631 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
633 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
635 // find all the records that have the same street address BUT not in a household
636 // require match on city and state as well
638 SELECT r1.id as master_id,
639 r1.civicrm_primary_id as master_contact_id,
640 r1.postal_greeting as master_postal_greeting,
641 r1.postal_greeting_id as master_postal_greeting_id,
642 r1.addressee as master_addressee,
643 r1.addressee_id as master_addressee_id,
645 r2.civicrm_primary_id as copy_contact_id,
646 r2.postal_greeting as copy_postal_greeting,
647 r2.postal_greeting_id as copy_postal_greeting_id,
648 r2.addressee as copy_addressee,
649 r2.addressee_id as copy_addressee_id
651 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
652 r1.city = r2.city AND
653 r1.state_province_id = r2.state_province_id )
654 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
655 AND ( r2.household_name IS NULL OR r2.household_name = '' )
656 AND ( r1.street_address != '' )
660 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
662 // unset ids from $merge already present in $linkedMerge
663 foreach ($linkedMerge as $masterID => $values) {
665 $keys = array_merge($keys, array_keys($values['copy']));
666 foreach ($merge as $mid => $vals) {
667 if (in_array($mid, $keys)) {
671 foreach ($values['copy'] as $copyId) {
672 if (in_array($copyId, $keys)) {
673 unset($merge[$mid]['copy'][$copyId]);
679 $merge = $merge +
$linkedMerge;
681 foreach ($merge as $masterID => $values) {
684 SET addressee = %1, postal_greeting = %2, email_greeting = %3
688 1 => [$values['addressee'], 'String'],
689 2 => [$values['postalGreeting'], 'String'],
690 3 => [$values['emailGreeting'], 'String'],
691 4 => [$masterID, 'Integer'],
693 CRM_Core_DAO
::executeQuery($sql, $params);
696 $deleteIDs = array_keys($values['copy']);
697 $deleteIDString = implode(',', $deleteIDs);
699 DELETE FROM $tableName
700 WHERE id IN ( $deleteIDString )
702 CRM_Core_DAO
::executeQuery($sql);
705 // unset temporary columns that were added for postal mailing format
706 // @todo - this part is pretty close to ready to be removed....
707 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
708 $unsetKeys = array_keys($sqlColumns);
709 foreach ($unsetKeys as $headerKey => $sqlColKey) {
710 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
711 unset($sqlColumns[$sqlColKey]);
718 * @param int $contactId
719 * @param array $exportParams
723 public static function _replaceMergeTokens($contactId, $exportParams) {
731 foreach ($greetingFields as $greeting) {
732 if (!empty($exportParams[$greeting])) {
733 $greetingLabel = $exportParams[$greeting];
734 if (empty($contact)) {
739 $contact = civicrm_api('contact', 'get', $values);
741 if (!empty($contact['is_error'])) {
744 $contact = $contact['values'][$contact['id']];
747 $tokens = ['contact' => $greetingLabel];
748 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
755 * The function unsets static part of the string, if token is the dynamic part.
757 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
758 * i.e 'Hello Alan' => converted to => 'Alan'
760 * @param string $parsedString
761 * @param string $defaultGreeting
762 * @param bool $addressMergeGreetings
763 * @param string $greetingType
767 public static function _trimNonTokens(
768 &$parsedString, $defaultGreeting,
769 $addressMergeGreetings, $greetingType = 'postal_greeting'
771 if (!empty($addressMergeGreetings[$greetingType])) {
772 $greetingLabel = $addressMergeGreetings[$greetingType];
774 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
776 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
777 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
778 foreach ($stringsToBeReplaced as $key => $string) {
780 $stringsToBeReplaced[$key] = ltrim($string);
782 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
784 return $parsedString;
789 * @param array $exportParams
790 * @param bool $sharedAddress
794 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
795 static $contactGreetingTokens = [];
797 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
798 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
800 $merge = $parents = [];
801 $dao = CRM_Core_DAO
::executeQuery($sql);
803 while ($dao->fetch()) {
804 $masterID = $dao->master_id
;
805 $copyID = $dao->copy_id
;
806 $masterPostalGreeting = $dao->master_postal_greeting
;
807 $masterAddressee = $dao->master_addressee
;
808 $copyAddressee = $dao->copy_addressee
;
810 if (!$sharedAddress) {
811 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
812 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
814 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
815 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
817 $masterAddressee = CRM_Utils_Array
::value('addressee',
818 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
821 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
822 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
824 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
825 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
827 $copyAddressee = CRM_Utils_Array
::value('addressee',
828 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
832 if (!isset($merge[$masterID])) {
833 // check if this is an intermediate child
834 // this happens if there are 3 or more matches a,b, c
835 // the above query will return a, b / a, c / b, c
836 // we might be doing a bit more work, but for now its ok, unless someone
837 // knows how to fix the query above
838 if (isset($parents[$masterID])) {
839 $masterID = $parents[$masterID];
842 $merge[$masterID] = [
843 'addressee' => $masterAddressee,
845 'postalGreeting' => $masterPostalGreeting,
847 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
850 $parents[$copyID] = $masterID;
852 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
854 if (!empty($exportParams['postal_greeting_other']) &&
855 count($merge[$masterID]['copy']) >= 1
857 // use static greetings specified if no of contacts > 2
858 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
860 elseif ($copyPostalGreeting) {
861 self
::_trimNonTokens($copyPostalGreeting,
862 $postalOptions[$dao->copy_postal_greeting_id
],
865 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
866 // if there happens to be a duplicate, remove it
867 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
870 if (!empty($exportParams['addressee_other']) &&
871 count($merge[$masterID]['copy']) >= 1
873 // use static greetings specified if no of contacts > 2
874 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
876 elseif ($copyAddressee) {
877 self
::_trimNonTokens($copyAddressee,
878 $addresseeOptions[$dao->copy_addressee_id
],
879 $exportParams, 'addressee'
881 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
884 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
893 * @param \CRM_Export_BAO_ExportProcessor $processor
895 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
896 $exportTempTable = $processor->getTemporaryTable();
897 $exportMode = $processor->getExportMode();
900 $limit = self
::EXPORT_ROW_COUNT
;
902 $query = "SELECT * FROM $exportTempTable";
905 $limitQuery = $query . "
906 LIMIT $offset, $limit
908 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
914 $componentDetails = [];
915 while ($dao->fetch()) {
918 foreach ($sqlColumns as $column => $dontCare) {
919 $row[$column] = $dao->$column;
921 $componentDetails[] = $row;
923 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
930 $writeHeader = FALSE;
936 * Build componentPayment fields.
938 * This is no longer used by export but BAO_Mapping still calls it & we
939 * should find a generic way to handle this or move this to that class.
943 public static function componentPaymentFields() {
944 static $componentPaymentFields;
945 if (!isset($componentPaymentFields)) {
946 $componentPaymentFields = [
947 'componentPaymentField_total_amount' => ts('Total Amount'),
948 'componentPaymentField_contribution_status' => ts('Contribution Status'),
949 'componentPaymentField_received_date' => ts('Date Received'),
950 'componentPaymentField_payment_instrument' => ts('Payment Method'),
951 'componentPaymentField_transaction_id' => ts('Transaction ID'),
954 return $componentPaymentFields;
958 * Get the various arrays that we use to structure our output.
960 * The extraction of these has been moved to a separate function for clarity and so that
961 * tests can be added - in particular on the $outputHeaders array.
963 * However it still feels a bit like something that I'm too polite to write down and this should be seen
964 * as a step on the refactoring path rather than how it should be.
966 * @param array $returnProperties
967 * @param \CRM_Export_BAO_ExportProcessor $processor
970 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
971 * alias for the field generated by BAO_Query object.
972 * - headerRows Array of the column header strings to put in the csv header - non-associative.
973 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
974 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
975 * I'm too embarassed to discuss here.
977 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
978 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
979 * in the main DAO loop is done once per row & that coule be 100,000 times.)
980 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
981 * - a) the function used is more efficient or
982 * - b) this code is old & outdated. Submit your answers to circular bin or better
983 * yet find a way to comment them for posterity.
985 public static function getExportStructureArrays($returnProperties, $processor) {
986 $outputColumns = $metadata = [];
987 $queryFields = $processor->getQueryFields();
988 foreach ($returnProperties as $key => $value) {
989 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
990 $outputColumns[$key] = $value;
991 $processor->addOutputSpecification($key);
993 elseif ($processor->isRelationshipTypeKey($key)) {
994 $outputColumns[$key] = $value;
995 foreach ($value as $relationField => $relationValue) {
996 // below block is same as primary block (duplicate)
997 if (isset($queryFields[$relationField]['title'])) {
998 $processor->addOutputSpecification($relationField, $key);
1000 elseif (is_array($relationValue) && $relationField == 'location') {
1001 // fix header for location type case
1002 foreach ($relationValue as $ltype => $val) {
1003 foreach (array_keys($val) as $fld) {
1004 $type = explode('-', $fld);
1005 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array
::value(1, $type));
1012 foreach ($value as $locationType => $locationFields) {
1013 foreach (array_keys($locationFields) as $locationFieldName) {
1014 $type = explode('-', $locationFieldName);
1016 $actualDBFieldName = $type[0];
1017 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1019 if (!empty($type[1])) {
1020 $daoFieldName .= "-" . $type[1];
1022 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array
::value(1, $type));
1023 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
1024 $outputColumns[$daoFieldName] = TRUE;
1029 return [$outputColumns, $metadata];
1033 * Get the values of linked household contact.
1035 * @param CRM_Core_DAO $relDAO
1036 * @param array $value
1037 * @param string $field
1040 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1041 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1042 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1043 $i18n = CRM_Core_I18n
::singleton();
1044 $field = $field . '_';
1046 foreach ($value as $relationField => $relationValue) {
1047 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1048 $fieldValue = $relDAO->$relationField;
1049 if ($relationField == 'phone_type_id') {
1050 $fieldValue = $phoneTypes[$relationValue];
1052 elseif ($relationField == 'provider_id') {
1053 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1056 elseif (is_object($relDAO) && in_array($relationField, [
1061 //special case for greeting replacement
1062 $fldValue = "{$relationField}_display";
1063 $fieldValue = $relDAO->$fldValue;
1066 elseif (is_object($relDAO) && $relationField == 'state_province') {
1067 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1069 elseif (is_object($relDAO) && $relationField == 'country') {
1070 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1075 $relPrefix = $field . $relationField;
1077 if (is_object($relDAO) && $relationField == 'id') {
1078 $row[$relPrefix] = $relDAO->contact_id
;
1080 elseif (is_array($relationValue) && $relationField == 'location') {
1081 foreach ($relationValue as $ltype => $val) {
1082 // If the location name has a space in it the we need to handle that. This
1083 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1084 // improve it should be secure in the knowled it will be caught.
1085 $ltype = str_replace(' ', '_', $ltype);
1086 foreach (array_keys($val) as $fld) {
1087 $type = explode('-', $fld);
1088 $fldValue = "{$ltype}-" . $type[0];
1089 if (!empty($type[1])) {
1090 $fldValue .= "-" . $type[1];
1092 // CRM-3157: localise country, region (both have ‘country’ context)
1093 // and state_province (‘province’ context)
1095 case (!is_object($relDAO)):
1096 $row[$field . '_' . $fldValue] = '';
1099 case in_array('country', $type):
1100 case in_array('world_region', $type):
1101 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1102 ['context' => 'country']
1106 case in_array('state_province', $type):
1107 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1108 ['context' => 'province']
1113 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1119 elseif (isset($fieldValue) && $fieldValue != '') {
1120 //check for custom data
1121 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1122 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1125 //normal relationship fields
1126 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1127 switch ($relationField) {
1129 case 'world_region':
1130 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1133 case 'state_province':
1134 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1138 $row[$relPrefix] = $fieldValue;
1144 // if relation field is empty or null
1145 $row[$relPrefix] = '';
1151 * Get the ids that we want to get related contact details for.
1154 * @param int $exportMode
1158 protected static function getIDsForRelatedContact($ids, $exportMode) {
1159 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1162 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1164 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1165 $dao = CRM_Core_DAO
::executeQuery("
1166 SELECT contact_id FROM civicrm_activity_contact
1167 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1168 record_type_id = {$sourceID}
1171 while ($dao->fetch()) {
1172 $relIDs[] = $dao->contact_id
;
1176 $component = self
::exportComponent($exportMode);
1178 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1179 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1182 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1189 * @param \CRM_Export_BAO_ExportProcessor $processor
1190 * @param $componentTable
1192 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1193 $allRelContactArray = $relationQuery = [];
1194 $queryMode = $processor->getQueryMode();
1195 $exportMode = $processor->getExportMode();
1197 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1198 $allRelContactArray[$relationshipKey] = [];
1199 // build Query for each relationship
1200 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1201 NULL, FALSE, FALSE, $queryMode
1203 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1205 list($id, $direction) = explode('_', $relationshipKey, 2);
1206 // identify the relationship direction
1207 $contactA = 'contact_id_a';
1208 $contactB = 'contact_id_b';
1209 if ($direction == 'b_a') {
1210 $contactA = 'contact_id_b';
1211 $contactB = 'contact_id_a';
1213 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1215 $relationshipJoin = $relationshipClause = '';
1216 if (!$selectAll && $componentTable) {
1217 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1219 elseif (!empty($relIDs)) {
1220 $relID = implode(',', $relIDs);
1221 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1224 $relationFrom = " {$relationFrom}
1225 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1226 {$relationshipJoin} ";
1228 //check for active relationship status only
1229 $today = date('Ymd');
1230 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1231 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1232 CRM_Core_DAO
::disableFullGroupByMode();
1233 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1234 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1236 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1237 CRM_Core_DAO
::reenableFullGroupByMode();
1239 while ($allRelContactDAO->fetch()) {
1240 $relationQuery->convertToPseudoNames($allRelContactDAO);
1242 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1243 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1244 foreach (array_keys($relationReturnProperties) as $property) {
1245 if ($property === 'location') {
1246 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1247 // $processor->setRelationshipValue from fetchRelationshipDetails
1248 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1249 foreach (array_keys($locationValues) as $locationValue) {
1250 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1251 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1256 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);