3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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-2018
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 * Key representing the head of household in the relationship array.
47 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
51 protected static $relationshipTypes = [];
54 * Get default return property for export based on mode
56 * @param int $exportMode
59 * @return string $property
60 * Default Return property
62 public static function defaultReturnProperty($exportMode) {
63 // hack to add default return property based on export mode
65 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
66 $property = 'contribution_id';
68 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
69 $property = 'participant_id';
71 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
72 $property = 'membership_id';
74 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
75 $property = 'pledge_id';
77 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
78 $property = 'case_id';
80 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
81 $property = 'grant_id';
83 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
84 $property = 'activity_id';
90 * Get Export component
92 * @param int $exportMode
95 * @return string $component
96 * CiviCRM Export Component
98 public static function exportComponent($exportMode) {
99 switch ($exportMode) {
100 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
101 $component = 'civicrm_contribution';
104 case CRM_Export_Form_Select
::EVENT_EXPORT
:
105 $component = 'civicrm_participant';
108 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
109 $component = 'civicrm_membership';
112 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
113 $component = 'civicrm_pledge';
116 case CRM_Export_Form_Select
::GRANT_EXPORT
:
117 $component = 'civicrm_grant';
124 * Get Query Group By Clause
125 * @param \CRM_Export_BAO_ExportProcessor $processor
127 * @param array $returnProperties
129 * @param object $query
130 * CRM_Contact_BAO_Query
132 * @return string $groupBy
135 public static function getGroupBy($processor, $returnProperties, $query) {
137 $exportMode = $processor->getExportMode();
138 $queryMode = $processor->getQueryMode();
139 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
140 CRM_Utils_Array
::value('notes', $returnProperties) ||
142 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
144 $groupBy = "contact_a.id";
147 switch ($exportMode) {
148 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
149 $groupBy = 'civicrm_contribution.id';
150 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
151 // especial group by when soft credit columns are included
152 $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
156 case CRM_Export_Form_Select
::EVENT_EXPORT
:
157 $groupBy = 'civicrm_participant.id';
160 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
161 $groupBy = "civicrm_membership.id";
165 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
166 $groupBy = "civicrm_activity.id ";
169 if (!empty($groupBy)) {
170 if (!Civi
::settings()->get('searchPrimaryDetailsOnly')) {
171 CRM_Core_DAO
::disableFullGroupByMode();
173 $groupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($query->_select
, $groupBy);
180 * Get the list the export fields.
182 * @param int $selectAll
183 * User preference while export.
186 * @param array $params
187 * Associated array of fields.
188 * @param string $order
190 * @param array $fields
191 * Associated array of fields.
192 * @param array $moreReturnProperties
193 * Additional return fields.
194 * @param int $exportMode
196 * @param string $componentClause
198 * @param string $componentTable
200 * @param bool $mergeSameAddress
201 * Merge records if they have same address.
202 * @param bool $mergeSameHousehold
203 * Merge records if they belong to the same household.
205 * @param array $exportParams
206 * @param string $queryOperator
209 * An array can be requested from within a unit test.
211 * @throws \CRM_Core_Exception
213 public static function exportComponents(
219 $moreReturnProperties = NULL,
220 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
221 $componentClause = NULL,
222 $componentTable = NULL,
223 $mergeSameAddress = FALSE,
224 $mergeSameHousehold = FALSE,
225 $exportParams = array(),
226 $queryOperator = 'AND'
229 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold);
230 $returnProperties = array();
232 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
233 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
234 // without manually testing the export of IM provider still works.
235 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
236 self
::$relationshipTypes = $processor->getRelationshipTypes();
238 $queryMode = $processor->getQueryMode();
241 foreach ($fields as $key => $value) {
242 $fieldName = CRM_Utils_Array
::value(1, $value);
247 if ($processor->isRelationshipTypeKey($fieldName) && (!empty($value[2]) ||
!empty($value[4]))) {
248 $returnProperties[$fieldName] = $processor->setRelationshipReturnProperties($value, $fieldName);
250 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
251 $locationName = CRM_Core_PseudoConstant
::getName('CRM_Core_BAO_Address', 'location_type_id', $value[2]);
252 if ($fieldName == 'phone') {
253 $returnProperties['location'][$locationName]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
255 elseif ($fieldName == 'im') {
256 $returnProperties['location'][$locationName]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
259 $returnProperties['location'][$locationName][$fieldName] = 1;
263 //hack to fix component fields
264 //revert mix of event_id and title
265 if ($fieldName == 'event_id') {
266 $returnProperties['event_id'] = 1;
269 $returnProperties[$fieldName] = 1;
273 $defaultExportMode = self
::defaultReturnProperty($exportMode);
274 if ($defaultExportMode) {
275 $returnProperties[$defaultExportMode] = 1;
279 $returnProperties = $processor->getDefaultReturnProperties();
281 // @todo - we are working towards this being entirely a property of the processor
282 $processor->setReturnProperties($returnProperties);
283 $paymentTableId = $processor->getPaymentTableID();
285 if ($mergeSameAddress) {
286 //make sure the addressee fields are selected
287 //while using merge same address feature
288 $returnProperties['addressee'] = 1;
289 $returnProperties['postal_greeting'] = 1;
290 $returnProperties['email_greeting'] = 1;
291 $returnProperties['street_name'] = 1;
292 $returnProperties['household_name'] = 1;
293 $returnProperties['street_address'] = 1;
294 $returnProperties['city'] = 1;
295 $returnProperties['state_province'] = 1;
297 // some columns are required for assistance incase they are not already present
298 $exportParams['merge_same_address']['temp_columns'] = array();
299 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
300 foreach ($tempColumns as $column) {
301 if (!array_key_exists($column, $returnProperties)) {
302 $returnProperties[$column] = 1;
303 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
304 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
309 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
310 // If an Additional Group is selected, then all contacts in that group are
311 // added to the export set (filtering out duplicates).
313 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";
314 CRM_Core_DAO
::executeQuery($query);
317 if ($moreReturnProperties) {
319 if (!empty($moreReturnProperties['group'])) {
320 unset($moreReturnProperties['group']);
321 $moreReturnProperties['groups'] = 1;
323 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
326 $exportParams['postal_mailing_export']['temp_columns'] = array();
327 if ($exportParams['exportOption'] == 2 &&
328 isset($exportParams['postal_mailing_export']) &&
329 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
331 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
332 foreach ($postalColumns as $column) {
333 if (!array_key_exists($column, $returnProperties)) {
334 $returnProperties[$column] = 1;
335 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
340 // rectify params to what proximity search expects if there is a value for prox_distance
342 if (!empty($params)) {
343 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
346 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
348 if ($mergeSameHousehold == 1) {
349 if (empty($returnProperties['id'])) {
350 $returnProperties['id'] = 1;
353 foreach ($returnProperties as $key => $value) {
354 if (!$processor->isRelationshipTypeKey($key)) {
355 foreach ($processor->getHouseholdRelationshipTypes() as $householdRelationshipType) {
356 if (!in_array($key, ['location_type', 'im_provider'])) {
357 $returnProperties[$householdRelationshipType][$key] = $value;
360 // @todo - don't use returnProperties above.
361 $processor->setHouseholdMergeReturnProperties($returnProperties[$householdRelationshipType]);
366 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
368 // make sure the groups stuff is included only if specifically specified
369 // by the fields param (CRM-1969), else we limit the contacts outputted to only
370 // ones that are part of a group
371 if (!empty($returnProperties['groups'])) {
372 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
373 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
374 // total hack for export, CRM-3618
375 $from = str_replace($oldClause,
381 if (!$selectAll && $componentTable) {
382 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
384 elseif ($componentClause) {
386 $where = "WHERE $componentClause";
389 $where .= " AND $componentClause";
393 // CRM-13982 - check if is deleted
394 $excludeTrashed = TRUE;
395 foreach ($params as $value) {
396 if ($value[0] == 'contact_is_deleted') {
397 $excludeTrashed = FALSE;
400 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
403 $where = "WHERE $trashClause";
406 $where .= " AND $trashClause";
409 $queryString = "$select $from $where $having";
411 $groupBy = self
::getGroupBy($processor, $returnProperties, $query);
413 $queryString .= $groupBy;
416 // always add contact_a.id to the ORDER clause
417 // so the order is deterministic
419 if (strpos('contact_a.id', $order) === FALSE) {
420 $order .= ", contact_a.id";
423 list($field, $dir) = explode(' ', $order, 2);
424 $field = trim($field);
425 if (!empty($returnProperties[$field])) {
427 $queryString .= " ORDER BY $order";
431 $addPaymentHeader = FALSE;
433 $paymentDetails = array();
434 if ($processor->isExportPaymentFields()) {
436 // get payment related in for event and members
437 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
438 //get all payment headers.
439 // If we haven't selected specific payment fields, load in all the
441 if (!$processor->isExportSpecifiedPaymentFields()) {
442 $paymentHeaders = self
::componentPaymentFields();
443 if (!empty($paymentDetails)) {
444 $addPaymentHeader = TRUE;
447 // If we have selected specific payment fields, leave the payment headers
448 // as an empty array; the headers for each selected field will be added
451 $paymentHeaders = array();
453 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
456 $componentDetails = array();
459 $rowCount = self
::EXPORT_ROW_COUNT
;
461 // we write to temp table often to avoid using too much memory
466 // for CRM-3157 purposes
467 $i18n = CRM_Core_I18n
::singleton();
469 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
471 $limitReached = FALSE;
472 while (!$limitReached) {
473 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
474 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
475 // If this is less than our limit by the end of the iteration we do not need to run the query again to
476 // check if some remain.
477 $rowsThisIteration = 0;
479 while ($iterationDAO->fetch()) {
481 $rowsThisIteration++
;
483 $query->convertToPseudoNames($iterationDAO);
485 //first loop through output columns so that we return what is required, and in same order.
486 foreach ($outputColumns as $field => $value) {
488 // add im_provider to $dao object
489 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
490 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
493 //build row values (data)
495 if (property_exists($iterationDAO, $field)) {
496 $fieldValue = $iterationDAO->$field;
497 // to get phone type from phone type id
498 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
499 $fieldValue = $phoneTypes[$fieldValue];
501 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
502 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
504 elseif (strstr($field, 'master_id')) {
505 $masterAddressId = NULL;
506 if (isset($iterationDAO->$field)) {
507 $masterAddressId = $iterationDAO->$field;
509 // get display name of contact that address is shared.
510 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
514 if ($processor->isRelationshipTypeKey($field)) {
515 foreach (array_keys($value) as $property) {
516 if ($property === 'location') {
517 // @todo just undo all this nasty location wrangling!
518 foreach ($value['location'] as $locationKey => $locationFields) {
519 foreach (array_keys($locationFields) as $locationField) {
520 $fieldKey = str_replace(' ', '_', $locationKey . '-' . $locationField);
521 $row[$field . '_' . $fieldKey] = $processor->getRelationshipValue($field, $iterationDAO->contact_id
, $fieldKey);
526 $row[$field . '_' . $property] = $processor->getRelationshipValue($field, $iterationDAO->contact_id
, $property);
531 $row[$field] = self
::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor);
535 // add payment headers if required
536 if ($addPaymentHeader && $processor->isExportPaymentFields()) {
537 // @todo rather than do this for every single row do it before the loop starts.
538 // where other header definitions take place.
539 $headerRows = array_merge($headerRows, $paymentHeaders);
540 foreach (array_keys($paymentHeaders) as $paymentHdr) {
541 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
546 $exportTempTable = self
::createTempTable($sqlColumns);
549 //build header only once
552 // If specific payment fields have been selected for export, payment
553 // data will already be in $row. Otherwise, add payment related
554 // information, if appropriate.
555 if ($addPaymentHeader) {
556 if (!$processor->isExportSpecifiedPaymentFields()) {
557 if ($processor->isExportPaymentFields()) {
558 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
559 if (!is_array($paymentData) ||
empty($paymentData)) {
560 $paymentData = $nullContributionDetails;
562 $row = array_merge($row, $paymentData);
564 elseif (!empty($paymentDetails)) {
565 $row = array_merge($row, $nullContributionDetails);
569 //remove organization name for individuals if it is set for current employer
570 if (!empty($row['contact_type']) &&
571 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
573 $row['organization_name'] = '';
576 // add component info
577 // write the row to a file
578 $componentDetails[] = $row;
580 // output every $tempRowCount rows
581 if ($count %
$tempRowCount == 0) {
582 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
583 $componentDetails = array();
586 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
587 $limitReached = TRUE;
589 $offset +
= $rowCount;
592 if ($exportTempTable) {
593 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
595 // if postalMailing option is checked, exclude contacts who are deceased, have
596 // "Do not mail" privacy setting, or have no street address
597 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
598 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
600 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
603 // do merge same address and merge same household processing
604 if ($mergeSameAddress) {
605 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
608 // merge the records if they have corresponding households
609 if ($mergeSameHousehold) {
610 foreach ($processor->getHouseholdRelationshipTypes() as $householdRelationshipType) {
611 self
::mergeSameHousehold($exportTempTable, $sqlColumns, $householdRelationshipType);
616 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
618 // In order to be able to write a unit test against this function we need to suppress
619 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
620 if (empty($exportParams['suppress_csv_for_testing'])) {
621 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor);
624 // return tableName sqlColumns headerRows in test context
625 return array($exportTempTable, $sqlColumns, $headerRows);
628 // delete the export temp table and component table
629 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
630 CRM_Core_DAO
::executeQuery($sql);
631 CRM_Core_DAO
::reenableFullGroupByMode();
632 CRM_Utils_System
::civiExit();
635 CRM_Core_DAO
::reenableFullGroupByMode();
636 throw new CRM_Core_Exception(ts('No records to export'));
641 * Handle import error file creation.
643 public static function invoke() {
644 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
645 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
646 if (empty($parserName) ||
empty($type)) {
650 // clean and ensure parserName is a valid string
651 $parserName = CRM_Utils_String
::munge($parserName);
652 $parserClass = explode('_', $parserName);
654 // make sure parserClass is in the CRM namespace and
655 // at least 3 levels deep
656 if ($parserClass[0] == 'CRM' &&
657 count($parserClass) >= 3
659 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
660 // ensure the functions exists
661 if (method_exists($parserName, 'errorFileName') &&
662 method_exists($parserName, 'saveFileName')
664 $errorFileName = $parserName::errorFileName($type);
665 $saveFileName = $parserName::saveFileName($type);
666 if (!empty($errorFileName) && !empty($saveFileName)) {
667 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
668 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
669 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
670 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
671 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
673 readfile($errorFileName);
677 CRM_Utils_System
::civiExit();
681 * @param $customSearchClass
685 public static function exportCustom($customSearchClass, $formValues, $order) {
686 $ext = CRM_Extension_System
::singleton()->getMapper();
687 if (!$ext->isExtensionClass($customSearchClass)) {
688 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
691 require_once $ext->classToPath($customSearchClass);
693 $search = new $customSearchClass($formValues);
695 $includeContactIDs = FALSE;
696 if ($formValues['radio_ts'] == 'ts_sel') {
697 $includeContactIDs = TRUE;
700 $sql = $search->all(0, 0, $order, $includeContactIDs);
702 $columns = $search->columns();
704 $header = array_keys($columns);
705 $fields = array_values($columns);
708 $dao = CRM_Core_DAO
::executeQuery($sql);
710 if (method_exists($search, 'alterRow')) {
713 while ($dao->fetch()) {
716 foreach ($fields as $field) {
717 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
718 $row[$field] = $dao->$unqualified_field;
721 $search->alterRow($row);
726 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
727 CRM_Utils_System
::civiExit();
731 * @param \CRM_Export_BAO_ExportProcessor $processor
735 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
736 $sqlColumns[$processor->getMungedFieldName($field)] = $processor->getSqlColumnDefinition($field);
740 * @param string $tableName
744 public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
745 if (empty($details)) {
754 $id = CRM_Core_DAO
::singleValueQuery($sql);
759 $sqlClause = array();
761 foreach ($details as $row) {
763 $valueString = array($id);
764 foreach ($row as $value) {
766 $valueString[] = "''";
769 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
772 $sqlClause[] = '(' . implode(',', $valueString) . ')';
775 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
777 $sqlValueString = implode(",\n", $sqlClause);
780 INSERT INTO $tableName $sqlColumnString
781 VALUES $sqlValueString
783 CRM_Core_DAO
::executeQuery($sql);
791 public static function createTempTable($sqlColumns) {
792 //creating a temporary table for the search result that need be exported
793 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
795 // also create the sql table
796 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
797 CRM_Core_DAO
::executeQuery($sql);
800 CREATE TABLE {$exportTempTable} (
801 id int unsigned NOT NULL AUTO_INCREMENT,
803 $sql .= implode(",\n", array_values($sqlColumns));
808 // add indexes for street_address and household_name if present
812 'civicrm_primary_id',
815 foreach ($addIndices as $index) {
816 if (isset($sqlColumns[$index])) {
818 INDEX index_{$index}( $index )
824 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
827 CRM_Core_DAO
::executeQuery($sql);
828 return $exportTempTable;
832 * @param string $tableName
835 * @param array $exportParams
837 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
838 // check if any records are present based on if they have used shared address feature,
839 // and not based on if city / state .. matches.
841 SELECT r1.id as copy_id,
842 r1.civicrm_primary_id as copy_contact_id,
843 r1.addressee as copy_addressee,
844 r1.addressee_id as copy_addressee_id,
845 r1.postal_greeting as copy_postal_greeting,
846 r1.postal_greeting_id as copy_postal_greeting_id,
848 r2.civicrm_primary_id as master_contact_id,
849 r2.postal_greeting as master_postal_greeting,
850 r2.postal_greeting_id as master_postal_greeting_id,
851 r2.addressee as master_addressee,
852 r2.addressee_id as master_addressee_id
854 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
855 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
857 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
859 // find all the records that have the same street address BUT not in a household
860 // require match on city and state as well
862 SELECT r1.id as master_id,
863 r1.civicrm_primary_id as master_contact_id,
864 r1.postal_greeting as master_postal_greeting,
865 r1.postal_greeting_id as master_postal_greeting_id,
866 r1.addressee as master_addressee,
867 r1.addressee_id as master_addressee_id,
869 r2.civicrm_primary_id as copy_contact_id,
870 r2.postal_greeting as copy_postal_greeting,
871 r2.postal_greeting_id as copy_postal_greeting_id,
872 r2.addressee as copy_addressee,
873 r2.addressee_id as copy_addressee_id
875 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
876 r1.city = r2.city AND
877 r1.state_province_id = r2.state_province_id )
878 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
879 AND ( r2.household_name IS NULL OR r2.household_name = '' )
880 AND ( r1.street_address != '' )
884 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
886 // unset ids from $merge already present in $linkedMerge
887 foreach ($linkedMerge as $masterID => $values) {
888 $keys = array($masterID);
889 $keys = array_merge($keys, array_keys($values['copy']));
890 foreach ($merge as $mid => $vals) {
891 if (in_array($mid, $keys)) {
895 foreach ($values['copy'] as $copyId) {
896 if (in_array($copyId, $keys)) {
897 unset($merge[$mid]['copy'][$copyId]);
903 $merge = $merge +
$linkedMerge;
905 foreach ($merge as $masterID => $values) {
908 SET addressee = %1, postal_greeting = %2, email_greeting = %3
912 1 => array($values['addressee'], 'String'),
913 2 => array($values['postalGreeting'], 'String'),
914 3 => array($values['emailGreeting'], 'String'),
915 4 => array($masterID, 'Integer'),
917 CRM_Core_DAO
::executeQuery($sql, $params);
920 $deleteIDs = array_keys($values['copy']);
921 $deleteIDString = implode(',', $deleteIDs);
923 DELETE FROM $tableName
924 WHERE id IN ( $deleteIDString )
926 CRM_Core_DAO
::executeQuery($sql);
929 // unset temporary columns that were added for postal mailing format
930 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
931 $unsetKeys = array_keys($sqlColumns);
932 foreach ($unsetKeys as $headerKey => $sqlColKey) {
933 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
934 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
941 * @param int $contactId
942 * @param array $exportParams
946 public static function _replaceMergeTokens($contactId, $exportParams) {
947 $greetings = array();
950 $greetingFields = array(
954 foreach ($greetingFields as $greeting) {
955 if (!empty($exportParams[$greeting])) {
956 $greetingLabel = $exportParams[$greeting];
957 if (empty($contact)) {
962 $contact = civicrm_api('contact', 'get', $values);
964 if (!empty($contact['is_error'])) {
967 $contact = $contact['values'][$contact['id']];
970 $tokens = array('contact' => $greetingLabel);
971 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
978 * The function unsets static part of the string, if token is the dynamic part.
980 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
981 * i.e 'Hello Alan' => converted to => 'Alan'
983 * @param string $parsedString
984 * @param string $defaultGreeting
985 * @param bool $addressMergeGreetings
986 * @param string $greetingType
990 public static function _trimNonTokens(
991 &$parsedString, $defaultGreeting,
992 $addressMergeGreetings, $greetingType = 'postal_greeting'
994 if (!empty($addressMergeGreetings[$greetingType])) {
995 $greetingLabel = $addressMergeGreetings[$greetingType];
997 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
999 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1000 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1001 foreach ($stringsToBeReplaced as $key => $string) {
1002 // to keep one space
1003 $stringsToBeReplaced[$key] = ltrim($string);
1005 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1007 return $parsedString;
1012 * @param array $exportParams
1013 * @param bool $sharedAddress
1017 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1018 static $contactGreetingTokens = array();
1020 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1021 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1023 $merge = $parents = array();
1024 $dao = CRM_Core_DAO
::executeQuery($sql);
1026 while ($dao->fetch()) {
1027 $masterID = $dao->master_id
;
1028 $copyID = $dao->copy_id
;
1029 $masterPostalGreeting = $dao->master_postal_greeting
;
1030 $masterAddressee = $dao->master_addressee
;
1031 $copyAddressee = $dao->copy_addressee
;
1033 if (!$sharedAddress) {
1034 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1035 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1037 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1038 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1040 $masterAddressee = CRM_Utils_Array
::value('addressee',
1041 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1044 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1045 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1047 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1048 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1050 $copyAddressee = CRM_Utils_Array
::value('addressee',
1051 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1055 if (!isset($merge[$masterID])) {
1056 // check if this is an intermediate child
1057 // this happens if there are 3 or more matches a,b, c
1058 // the above query will return a, b / a, c / b, c
1059 // we might be doing a bit more work, but for now its ok, unless someone
1060 // knows how to fix the query above
1061 if (isset($parents[$masterID])) {
1062 $masterID = $parents[$masterID];
1065 $merge[$masterID] = array(
1066 'addressee' => $masterAddressee,
1068 'postalGreeting' => $masterPostalGreeting,
1070 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1073 $parents[$copyID] = $masterID;
1075 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1077 if (!empty($exportParams['postal_greeting_other']) &&
1078 count($merge[$masterID]['copy']) >= 1
1080 // use static greetings specified if no of contacts > 2
1081 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1083 elseif ($copyPostalGreeting) {
1084 self
::_trimNonTokens($copyPostalGreeting,
1085 $postalOptions[$dao->copy_postal_greeting_id
],
1088 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1089 // if there happens to be a duplicate, remove it
1090 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1093 if (!empty($exportParams['addressee_other']) &&
1094 count($merge[$masterID]['copy']) >= 1
1096 // use static greetings specified if no of contacts > 2
1097 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1099 elseif ($copyAddressee) {
1100 self
::_trimNonTokens($copyAddressee,
1101 $addresseeOptions[$dao->copy_addressee_id
],
1102 $exportParams, 'addressee'
1104 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1107 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1114 * Merge household record into the individual record
1117 * @param string $exportTempTable
1118 * Temporary temp table that stores the records.
1119 * @param array $sqlColumns
1120 * Array of names of the table columns of the temp table.
1121 * @param string $prefix
1122 * Name of the relationship type that is prefixed to the table columns.
1124 public static function mergeSameHousehold($exportTempTable, &$sqlColumns, $prefix) {
1125 $prefixColumn = $prefix . '_';
1126 $replaced = array();
1128 // name map of the non standard fields in header rows & sql columns
1129 $mappingFields = array(
1130 'civicrm_primary_id' => 'id',
1131 'provider_id' => 'im_service_provider',
1132 'phone_type_id' => 'phone_type',
1135 //figure out which columns are to be replaced by which ones
1136 foreach ($sqlColumns as $columnNames => $dontCare) {
1137 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1138 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1141 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1143 if (!empty($sqlColumns[$householdColName])) {
1144 $replaced[$columnNames] = $householdColName;
1148 $query = "UPDATE $exportTempTable SET ";
1151 foreach ($replaced as $from => $to) {
1152 $clause[] = "$from = $to ";
1153 unset($sqlColumns[$to]);
1155 $query .= implode(",\n", $clause);
1156 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1158 CRM_Core_DAO
::executeQuery($query);
1160 //drop the table columns that store redundant household info
1161 $dropQuery = "ALTER TABLE $exportTempTable ";
1162 foreach ($replaced as $householdColumns) {
1163 $dropClause[] = " DROP $householdColumns ";
1165 $dropQuery .= implode(",\n", $dropClause);
1167 CRM_Core_DAO
::executeQuery($dropQuery);
1169 // also drop the temp table if exists
1170 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1171 CRM_Core_DAO
::executeQuery($sql);
1173 // clean up duplicate records
1175 CREATE TABLE {$exportTempTable}_temp SELECT *
1176 FROM {$exportTempTable}
1177 GROUP BY civicrm_primary_id ";
1179 CRM_Core_DAO
::executeQuery($query);
1181 $query = "DROP TABLE $exportTempTable";
1182 CRM_Core_DAO
::executeQuery($query);
1184 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1185 CRM_Core_DAO
::executeQuery($query);
1189 * @param $exportTempTable
1190 * @param $headerRows
1191 * @param $sqlColumns
1192 * @param \CRM_Export_BAO_ExportProcessor $processor
1194 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $processor) {
1195 $exportMode = $processor->getExportMode();
1196 $writeHeader = TRUE;
1198 $limit = self
::EXPORT_ROW_COUNT
;
1200 $query = "SELECT * FROM $exportTempTable";
1203 $limitQuery = $query . "
1204 LIMIT $offset, $limit
1206 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1212 $componentDetails = array();
1213 while ($dao->fetch()) {
1216 foreach ($sqlColumns as $column => $dontCare) {
1217 $row[$column] = $dao->$column;
1219 $componentDetails[] = $row;
1221 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
1228 $writeHeader = FALSE;
1234 * Manipulate header rows for relationship fields.
1236 * @param $headerRows
1238 public static function manipulateHeaderRows(&$headerRows) {
1239 foreach ($headerRows as & $header) {
1240 $split = explode('-', $header);
1241 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1242 $split[0] = $relationTypeName;
1243 $header = implode('-', $split);
1249 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1250 * or have no street address
1251 * @param $exportTempTable
1252 * @param $headerRows
1253 * @param $sqlColumns
1254 * @param $exportParams
1256 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1257 $whereClause = array();
1259 if (array_key_exists('is_deceased', $sqlColumns)) {
1260 $whereClause[] = 'is_deceased = 1';
1263 if (array_key_exists('do_not_mail', $sqlColumns)) {
1264 $whereClause[] = 'do_not_mail = 1';
1267 if (array_key_exists('street_address', $sqlColumns)) {
1268 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1270 // check for supplemental_address_1
1271 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1272 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1273 'address_options', TRUE, NULL, TRUE
1275 if (!empty($addressOptions['supplemental_address_1'])) {
1276 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1277 // enclose it again, since we are doing an AND in between a set of ORs
1278 $addressWhereClause = "( $addressWhereClause )";
1282 $whereClause[] = $addressWhereClause;
1285 if (!empty($whereClause)) {
1286 $whereClause = implode(' OR ', $whereClause);
1289 FROM $exportTempTable
1290 WHERE {$whereClause}";
1291 CRM_Core_DAO
::singleValueQuery($query);
1294 // unset temporary columns that were added for postal mailing format
1295 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1296 $unsetKeys = array_keys($sqlColumns);
1297 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1298 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1299 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1306 * Build componentPayment fields.
1308 public static function componentPaymentFields() {
1309 static $componentPaymentFields;
1310 if (!isset($componentPaymentFields)) {
1311 $componentPaymentFields = array(
1312 'componentPaymentField_total_amount' => ts('Total Amount'),
1313 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1314 'componentPaymentField_received_date' => ts('Date Received'),
1315 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1316 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1319 return $componentPaymentFields;
1323 * Set the definition for the header rows and sql columns based on the field to output.
1325 * @param string $field
1326 * @param array $headerRows
1327 * @param \CRM_Export_BAO_ExportProcessor $processor
1331 public static function setHeaderRows($field, $headerRows, $processor) {
1333 $queryFields = $processor->getQueryFields();
1334 if (substr($field, -11) == 'campaign_id') {
1335 // @todo - set this correctly in the xml rather than here.
1336 $headerRows[] = ts('Campaign ID');
1338 elseif ($processor->isMergeSameHousehold() && $field === 'id') {
1339 $headerRows[] = ts('Household ID');
1341 elseif (isset($queryFields[$field]['title'])) {
1342 $headerRows[] = $queryFields[$field]['title'];
1344 elseif ($field == 'provider_id') {
1345 // @todo - set this correctly in the xml rather than here.
1346 $headerRows[] = ts('IM Service Provider');
1348 elseif ($processor->isExportPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1349 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1352 $headerRows[] = $field;
1359 * Get the various arrays that we use to structure our output.
1361 * The extraction of these has been moved to a separate function for clarity and so that
1362 * tests can be added - in particular on the $outputHeaders array.
1364 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1365 * as a step on the refactoring path rather than how it should be.
1367 * @param array $returnProperties
1368 * @param \CRM_Export_BAO_ExportProcessor $processor
1371 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1372 * alias for the field generated by BAO_Query object.
1373 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1374 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1375 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1376 * I'm too embarassed to discuss here.
1378 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1379 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1380 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1381 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1382 * - a) the function used is more efficient or
1383 * - b) this code is old & outdated. Submit your answers to circular bin or better
1384 * yet find a way to comment them for posterity.
1386 public static function getExportStructureArrays($returnProperties, $processor) {
1387 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1388 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1389 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1390 $queryFields = $processor->getQueryFields();
1391 foreach ($returnProperties as $key => $value) {
1392 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
1393 $outputColumns[$key] = $value;
1394 $headerRows = self
::setHeaderRows($key, $headerRows, $processor);
1395 self
::sqlColumnDefn($processor, $sqlColumns, $key);
1397 elseif ($processor->isRelationshipTypeKey($key)) {
1398 $outputColumns[$key] = $value;
1400 foreach ($value as $relationField => $relationValue) {
1401 // below block is same as primary block (duplicate)
1402 if (isset($queryFields[$relationField]['title'])) {
1403 $headerName = $field . '-' . $relationField;
1405 if (!$processor->isHouseholdMergeRelationshipTypeKey($field)) {
1406 // Do not add to header row if we are only generating for merge reasons.
1407 $headerRows[] = $headerName;
1410 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1412 elseif ($relationField == 'phone_type_id') {
1413 $headerName = $field . '-' . 'Phone Type';
1414 $headerRows[] = $headerName;
1415 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1417 elseif ($relationField == 'provider_id') {
1418 $headerName = $field . '-' . 'Im Service Provider';
1419 $headerRows[] = $headerName;
1420 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1422 elseif ($relationField == 'state_province_id') {
1423 $headerName = $field . '-' . 'state_province_id';
1424 $headerRows[] = $headerName;
1425 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1427 elseif (is_array($relationValue) && $relationField == 'location') {
1428 // fix header for location type case
1429 foreach ($relationValue as $ltype => $val) {
1430 foreach (array_keys($val) as $fld) {
1431 $type = explode('-', $fld);
1433 $hdr = "{$ltype}-" . $queryFields[$type[0]]['title'];
1435 if (!empty($type[1])) {
1436 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1437 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $type[1]);
1439 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1440 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_IM', 'provider_id', $type[1]);
1443 $headerName = $field . '-' . $hdr;
1444 $headerRows[] = $headerName;
1445 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1450 self
::manipulateHeaderRows($headerRows);
1453 foreach ($value as $locationType => $locationFields) {
1454 foreach (array_keys($locationFields) as $locationFieldName) {
1455 $type = explode('-', $locationFieldName);
1457 $actualDBFieldName = $type[0];
1458 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1459 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1461 if (!empty($type[1])) {
1462 $daoFieldName .= "-" . $type[1];
1463 if ($actualDBFieldName == 'phone') {
1464 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1466 elseif ($actualDBFieldName == 'im') {
1467 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1470 if ($type[0] == 'im_provider') {
1471 // Warning: shame inducing hack.
1472 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1474 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1475 $headerRows = self
::setHeaderRows($outputFieldName, $headerRows, $processor);
1476 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1477 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1478 $metadata[$daoFieldName] = array('context' => 'country');
1480 if ($actualDBFieldName == 'state_province') {
1481 $metadata[$daoFieldName] = array('context' => 'province');
1483 $outputColumns[$daoFieldName] = TRUE;
1488 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1492 * Get the values of linked household contact.
1494 * @param CRM_Core_DAO $relDAO
1495 * @param array $value
1496 * @param string $field
1499 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1500 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1501 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1502 $i18n = CRM_Core_I18n
::singleton();
1503 $field = $field . '_';
1505 foreach ($value as $relationField => $relationValue) {
1506 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1507 $fieldValue = $relDAO->$relationField;
1508 if ($relationField == 'phone_type_id') {
1509 $fieldValue = $phoneTypes[$relationValue];
1511 elseif ($relationField == 'provider_id') {
1512 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1515 elseif (is_object($relDAO) && in_array($relationField, array(
1521 //special case for greeting replacement
1522 $fldValue = "{$relationField}_display";
1523 $fieldValue = $relDAO->$fldValue;
1526 elseif (is_object($relDAO) && $relationField == 'state_province') {
1527 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1529 elseif (is_object($relDAO) && $relationField == 'country') {
1530 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1535 $relPrefix = $field . $relationField;
1537 if (is_object($relDAO) && $relationField == 'id') {
1538 $row[$relPrefix] = $relDAO->contact_id
;
1540 elseif (is_array($relationValue) && $relationField == 'location') {
1541 foreach ($relationValue as $ltype => $val) {
1542 // If the location name has a space in it the we need to handle that. This
1543 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1544 // improve it should be secure in the knowled it will be caught.
1545 $ltype = str_replace(' ', '_', $ltype);
1546 foreach (array_keys($val) as $fld) {
1547 $type = explode('-', $fld);
1548 $fldValue = "{$ltype}-" . $type[0];
1549 if (!empty($type[1])) {
1550 $fldValue .= "-" . $type[1];
1552 // CRM-3157: localise country, region (both have ‘country’ context)
1553 // and state_province (‘province’ context)
1555 case (!is_object($relDAO)):
1556 $row[$field . '_' . $fldValue] = '';
1559 case in_array('country', $type):
1560 case in_array('world_region', $type):
1561 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1562 array('context' => 'country')
1566 case in_array('state_province', $type):
1567 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1568 array('context' => 'province')
1573 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1579 elseif (isset($fieldValue) && $fieldValue != '') {
1580 //check for custom data
1581 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1582 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1585 //normal relationship fields
1586 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1587 switch ($relationField) {
1589 case 'world_region':
1590 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1593 case 'state_province':
1594 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1598 $row[$relPrefix] = $fieldValue;
1604 // if relation field is empty or null
1605 $row[$relPrefix] = '';
1611 * Get the ids that we want to get related contact details for.
1614 * @param int $exportMode
1618 protected static function getIDsForRelatedContact($ids, $exportMode) {
1619 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1622 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1624 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1625 $dao = CRM_Core_DAO
::executeQuery("
1626 SELECT contact_id FROM civicrm_activity_contact
1627 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1628 record_type_id = {$sourceID}
1631 while ($dao->fetch()) {
1632 $relIDs[] = $dao->contact_id
;
1636 $component = self
::exportComponent($exportMode);
1638 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1639 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1642 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1649 * @param \CRM_Export_BAO_ExportProcessor $processor
1650 * @param $componentTable
1652 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1653 $allRelContactArray = $relationQuery = array();
1654 $queryMode = $processor->getQueryMode();
1655 $exportMode = $processor->getExportMode();
1657 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1658 $allRelContactArray[$relationshipKey] = array();
1659 // build Query for each relationship
1660 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1661 NULL, FALSE, FALSE, $queryMode
1663 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1665 list($id, $direction) = explode('_', $relationshipKey, 2);
1666 // identify the relationship direction
1667 $contactA = 'contact_id_a';
1668 $contactB = 'contact_id_b';
1669 if ($direction == 'b_a') {
1670 $contactA = 'contact_id_b';
1671 $contactB = 'contact_id_a';
1673 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1675 $relationshipJoin = $relationshipClause = '';
1676 if (!$selectAll && $componentTable) {
1677 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1679 elseif (!empty($relIDs)) {
1680 $relID = implode(',', $relIDs);
1681 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1684 $relationFrom = " {$relationFrom}
1685 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1686 {$relationshipJoin} ";
1688 //check for active relationship status only
1689 $today = date('Ymd');
1690 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1691 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1692 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery->_select
, "crel.{$contactA}");
1693 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1694 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
1696 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1697 while ($allRelContactDAO->fetch()) {
1698 $relationQuery->convertToPseudoNames($allRelContactDAO);
1700 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1701 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1702 foreach (array_keys($relationReturnProperties) as $property) {
1703 if ($property === 'location') {
1704 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1705 // $processor->setRelationshipValue from fetchRelationshipDetails
1706 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1707 foreach (array_keys($locationValues) as $locationValue) {
1708 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1709 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
1714 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);
1723 * @param $iterationDAO
1724 * @param $fieldValue
1727 * @param $paymentDetails
1729 * @param \CRM_Export_BAO_ExportProcessor $processor
1733 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor) {
1735 if ($field == 'id') {
1736 return $iterationDAO->contact_id
;
1737 // special case for calculated field
1739 elseif ($field == 'source_contact_id') {
1740 return $iterationDAO->contact_id
;
1742 elseif ($field == 'pledge_balance_amount') {
1743 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1744 // special case for calculated field
1746 elseif ($field == 'pledge_next_pay_amount') {
1747 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1749 elseif (isset($fieldValue) &&
1752 //check for custom data
1753 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1754 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1757 elseif (in_array($field, array(
1762 //special case for greeting replacement
1763 $fldValue = "{$field}_display";
1764 return $iterationDAO->$fldValue;
1767 //normal fields with a touch of CRM-3157
1770 case 'world_region':
1771 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
1773 case 'state_province':
1774 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
1777 case 'preferred_communication_method':
1778 case 'preferred_mail_format':
1779 case 'communication_style':
1780 return $i18n->crm_translate($fieldValue);
1783 if (isset($metadata[$field])) {
1784 // No I don't know why we do it this way & whether we could
1785 // make better use of pseudoConstants.
1786 if (!empty($metadata[$field]['context'])) {
1787 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1789 if (!empty($metadata[$field]['pseudoconstant'])) {
1790 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1791 // call an external function until sure it is not increasing php processing given this
1792 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1793 // That can be next refactor...
1794 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1795 // but I have to reach a stable point....
1796 $varName = $metadata[$field]['pseudoconstant']['var'];
1797 if ($varName === 'imProviders') {
1798 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1800 if ($varName === 'phoneTypes') {
1801 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
1810 elseif ($processor->isExportSpecifiedPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1811 $paymentTableId = $processor->getPaymentTableID();
1812 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1813 $payFieldMapper = array(
1814 'componentPaymentField_total_amount' => 'total_amount',
1815 'componentPaymentField_contribution_status' => 'contribution_status',
1816 'componentPaymentField_payment_instrument' => 'pay_instru',
1817 'componentPaymentField_transaction_id' => 'trxn_id',
1818 'componentPaymentField_received_date' => 'receive_date',
1820 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1823 // if field is empty or null