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;
364 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable, $returnProperties);
366 // make sure the groups stuff is included only if specifically specified
367 // by the fields param (CRM-1969), else we limit the contacts outputted to only
368 // ones that are part of a group
369 if (!empty($returnProperties['groups'])) {
370 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
371 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
372 // total hack for export, CRM-3618
373 $from = str_replace($oldClause,
379 if (!$selectAll && $componentTable) {
380 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
382 elseif ($componentClause) {
384 $where = "WHERE $componentClause";
387 $where .= " AND $componentClause";
391 // CRM-13982 - check if is deleted
392 $excludeTrashed = TRUE;
393 foreach ($params as $value) {
394 if ($value[0] == 'contact_is_deleted') {
395 $excludeTrashed = FALSE;
398 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
401 $where = "WHERE $trashClause";
404 $where .= " AND $trashClause";
407 $queryString = "$select $from $where $having";
409 $groupBy = self
::getGroupBy($processor, $returnProperties, $query);
411 $queryString .= $groupBy;
414 // always add contact_a.id to the ORDER clause
415 // so the order is deterministic
417 if (strpos('contact_a.id', $order) === FALSE) {
418 $order .= ", contact_a.id";
421 list($field, $dir) = explode(' ', $order, 2);
422 $field = trim($field);
423 if (!empty($returnProperties[$field])) {
425 $queryString .= " ORDER BY $order";
429 $addPaymentHeader = FALSE;
431 $paymentDetails = array();
432 if ($processor->isExportPaymentFields()) {
434 // get payment related in for event and members
435 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
436 //get all payment headers.
437 // If we haven't selected specific payment fields, load in all the
439 if (!$processor->isExportSpecifiedPaymentFields()) {
440 $paymentHeaders = self
::componentPaymentFields();
441 if (!empty($paymentDetails)) {
442 $addPaymentHeader = TRUE;
445 // If we have selected specific payment fields, leave the payment headers
446 // as an empty array; the headers for each selected field will be added
449 $paymentHeaders = array();
451 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
454 $componentDetails = array();
457 $rowCount = self
::EXPORT_ROW_COUNT
;
459 // we write to temp table often to avoid using too much memory
464 // for CRM-3157 purposes
465 $i18n = CRM_Core_I18n
::singleton();
467 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
469 $limitReached = FALSE;
470 while (!$limitReached) {
471 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
472 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
473 // If this is less than our limit by the end of the iteration we do not need to run the query again to
474 // check if some remain.
475 $rowsThisIteration = 0;
477 while ($iterationDAO->fetch()) {
479 $rowsThisIteration++
;
481 $query->convertToPseudoNames($iterationDAO);
483 //first loop through output columns so that we return what is required, and in same order.
484 foreach ($outputColumns as $field => $value) {
486 // add im_provider to $dao object
487 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
488 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
491 //build row values (data)
493 if (property_exists($iterationDAO, $field)) {
494 $fieldValue = $iterationDAO->$field;
495 // to get phone type from phone type id
496 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
497 $fieldValue = $phoneTypes[$fieldValue];
499 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
500 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
502 elseif (strstr($field, 'master_id')) {
503 $masterAddressId = NULL;
504 if (isset($iterationDAO->$field)) {
505 $masterAddressId = $iterationDAO->$field;
507 // get display name of contact that address is shared.
508 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
512 if ($processor->isRelationshipTypeKey($field)) {
513 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
514 $relationQuery[$field]->convertToPseudoNames($relDAO);
515 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
518 $row[$field] = self
::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor);
522 // add payment headers if required
523 if ($addPaymentHeader && $processor->isExportPaymentFields()) {
524 // @todo rather than do this for every single row do it before the loop starts.
525 // where other header definitions take place.
526 $headerRows = array_merge($headerRows, $paymentHeaders);
527 foreach (array_keys($paymentHeaders) as $paymentHdr) {
528 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
533 $exportTempTable = self
::createTempTable($sqlColumns);
536 //build header only once
539 // If specific payment fields have been selected for export, payment
540 // data will already be in $row. Otherwise, add payment related
541 // information, if appropriate.
542 if ($addPaymentHeader) {
543 if (!$processor->isExportSpecifiedPaymentFields()) {
544 if ($processor->isExportPaymentFields()) {
545 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
546 if (!is_array($paymentData) ||
empty($paymentData)) {
547 $paymentData = $nullContributionDetails;
549 $row = array_merge($row, $paymentData);
551 elseif (!empty($paymentDetails)) {
552 $row = array_merge($row, $nullContributionDetails);
556 //remove organization name for individuals if it is set for current employer
557 if (!empty($row['contact_type']) &&
558 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
560 $row['organization_name'] = '';
563 // add component info
564 // write the row to a file
565 $componentDetails[] = $row;
567 // output every $tempRowCount rows
568 if ($count %
$tempRowCount == 0) {
569 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
570 $componentDetails = array();
573 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
574 $limitReached = TRUE;
576 $offset +
= $rowCount;
579 if ($exportTempTable) {
580 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
582 // if postalMailing option is checked, exclude contacts who are deceased, have
583 // "Do not mail" privacy setting, or have no street address
584 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
585 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
587 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
590 // do merge same address and merge same household processing
591 if ($mergeSameAddress) {
592 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
595 // merge the records if they have corresponding households
596 if ($mergeSameHousehold) {
597 foreach ($processor->getHouseholdRelationshipTypes() as $householdRelationshipType) {
598 self
::mergeSameHousehold($exportTempTable, $sqlColumns, $householdRelationshipType);
603 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
605 // In order to be able to write a unit test against this function we need to suppress
606 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
607 if (empty($exportParams['suppress_csv_for_testing'])) {
608 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
611 // return tableName sqlColumns headerRows in test context
612 return array($exportTempTable, $sqlColumns, $headerRows);
615 // delete the export temp table and component table
616 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
617 CRM_Core_DAO
::executeQuery($sql);
618 CRM_Core_DAO
::reenableFullGroupByMode();
619 CRM_Utils_System
::civiExit();
622 CRM_Core_DAO
::reenableFullGroupByMode();
623 throw new CRM_Core_Exception(ts('No records to export'));
628 * Name of the export file based on mode.
630 * @param string $output
638 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
640 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
641 return ts('CiviCRM Contact Search');
643 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
644 return ts('CiviCRM Contribution Search');
646 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
647 return ts('CiviCRM Member Search');
649 case CRM_Export_Form_Select
::EVENT_EXPORT
:
650 return ts('CiviCRM Participant Search');
652 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
653 return ts('CiviCRM Pledge Search');
655 case CRM_Export_Form_Select
::CASE_EXPORT
:
656 return ts('CiviCRM Case Search');
658 case CRM_Export_Form_Select
::GRANT_EXPORT
:
659 return ts('CiviCRM Grant Search');
661 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
662 return ts('CiviCRM Activity Search');
667 * Handle import error file creation.
669 public static function invoke() {
670 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
671 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
672 if (empty($parserName) ||
empty($type)) {
676 // clean and ensure parserName is a valid string
677 $parserName = CRM_Utils_String
::munge($parserName);
678 $parserClass = explode('_', $parserName);
680 // make sure parserClass is in the CRM namespace and
681 // at least 3 levels deep
682 if ($parserClass[0] == 'CRM' &&
683 count($parserClass) >= 3
685 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
686 // ensure the functions exists
687 if (method_exists($parserName, 'errorFileName') &&
688 method_exists($parserName, 'saveFileName')
690 $errorFileName = $parserName::errorFileName($type);
691 $saveFileName = $parserName::saveFileName($type);
692 if (!empty($errorFileName) && !empty($saveFileName)) {
693 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
694 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
695 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
696 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
697 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
699 readfile($errorFileName);
703 CRM_Utils_System
::civiExit();
707 * @param $customSearchClass
711 public static function exportCustom($customSearchClass, $formValues, $order) {
712 $ext = CRM_Extension_System
::singleton()->getMapper();
713 if (!$ext->isExtensionClass($customSearchClass)) {
714 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
717 require_once $ext->classToPath($customSearchClass);
719 $search = new $customSearchClass($formValues);
721 $includeContactIDs = FALSE;
722 if ($formValues['radio_ts'] == 'ts_sel') {
723 $includeContactIDs = TRUE;
726 $sql = $search->all(0, 0, $order, $includeContactIDs);
728 $columns = $search->columns();
730 $header = array_keys($columns);
731 $fields = array_values($columns);
734 $dao = CRM_Core_DAO
::executeQuery($sql);
736 if (method_exists($search, 'alterRow')) {
739 while ($dao->fetch()) {
742 foreach ($fields as $field) {
743 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
744 $row[$field] = $dao->$unqualified_field;
747 $search->alterRow($row);
752 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
753 CRM_Utils_System
::civiExit();
757 * @param \CRM_Export_BAO_ExportProcessor $processor
761 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
762 $sqlColumns[$processor->getMungedFieldName($field)] = $processor->getSqlColumnDefinition($field);
766 * @param string $tableName
770 public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
771 if (empty($details)) {
780 $id = CRM_Core_DAO
::singleValueQuery($sql);
785 $sqlClause = array();
787 foreach ($details as $row) {
789 $valueString = array($id);
790 foreach ($row as $value) {
792 $valueString[] = "''";
795 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
798 $sqlClause[] = '(' . implode(',', $valueString) . ')';
801 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
803 $sqlValueString = implode(",\n", $sqlClause);
806 INSERT INTO $tableName $sqlColumnString
807 VALUES $sqlValueString
809 CRM_Core_DAO
::executeQuery($sql);
817 public static function createTempTable($sqlColumns) {
818 //creating a temporary table for the search result that need be exported
819 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
821 // also create the sql table
822 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
823 CRM_Core_DAO
::executeQuery($sql);
826 CREATE TABLE {$exportTempTable} (
827 id int unsigned NOT NULL AUTO_INCREMENT,
829 $sql .= implode(",\n", array_values($sqlColumns));
834 // add indexes for street_address and household_name if present
838 'civicrm_primary_id',
841 foreach ($addIndices as $index) {
842 if (isset($sqlColumns[$index])) {
844 INDEX index_{$index}( $index )
850 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
853 CRM_Core_DAO
::executeQuery($sql);
854 return $exportTempTable;
858 * @param string $tableName
861 * @param array $exportParams
863 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
864 // check if any records are present based on if they have used shared address feature,
865 // and not based on if city / state .. matches.
867 SELECT r1.id as copy_id,
868 r1.civicrm_primary_id as copy_contact_id,
869 r1.addressee as copy_addressee,
870 r1.addressee_id as copy_addressee_id,
871 r1.postal_greeting as copy_postal_greeting,
872 r1.postal_greeting_id as copy_postal_greeting_id,
874 r2.civicrm_primary_id as master_contact_id,
875 r2.postal_greeting as master_postal_greeting,
876 r2.postal_greeting_id as master_postal_greeting_id,
877 r2.addressee as master_addressee,
878 r2.addressee_id as master_addressee_id
880 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
881 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
883 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
885 // find all the records that have the same street address BUT not in a household
886 // require match on city and state as well
888 SELECT r1.id as master_id,
889 r1.civicrm_primary_id as master_contact_id,
890 r1.postal_greeting as master_postal_greeting,
891 r1.postal_greeting_id as master_postal_greeting_id,
892 r1.addressee as master_addressee,
893 r1.addressee_id as master_addressee_id,
895 r2.civicrm_primary_id as copy_contact_id,
896 r2.postal_greeting as copy_postal_greeting,
897 r2.postal_greeting_id as copy_postal_greeting_id,
898 r2.addressee as copy_addressee,
899 r2.addressee_id as copy_addressee_id
901 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
902 r1.city = r2.city AND
903 r1.state_province_id = r2.state_province_id )
904 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
905 AND ( r2.household_name IS NULL OR r2.household_name = '' )
906 AND ( r1.street_address != '' )
910 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
912 // unset ids from $merge already present in $linkedMerge
913 foreach ($linkedMerge as $masterID => $values) {
914 $keys = array($masterID);
915 $keys = array_merge($keys, array_keys($values['copy']));
916 foreach ($merge as $mid => $vals) {
917 if (in_array($mid, $keys)) {
921 foreach ($values['copy'] as $copyId) {
922 if (in_array($copyId, $keys)) {
923 unset($merge[$mid]['copy'][$copyId]);
929 $merge = $merge +
$linkedMerge;
931 foreach ($merge as $masterID => $values) {
934 SET addressee = %1, postal_greeting = %2, email_greeting = %3
938 1 => array($values['addressee'], 'String'),
939 2 => array($values['postalGreeting'], 'String'),
940 3 => array($values['emailGreeting'], 'String'),
941 4 => array($masterID, 'Integer'),
943 CRM_Core_DAO
::executeQuery($sql, $params);
946 $deleteIDs = array_keys($values['copy']);
947 $deleteIDString = implode(',', $deleteIDs);
949 DELETE FROM $tableName
950 WHERE id IN ( $deleteIDString )
952 CRM_Core_DAO
::executeQuery($sql);
955 // unset temporary columns that were added for postal mailing format
956 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
957 $unsetKeys = array_keys($sqlColumns);
958 foreach ($unsetKeys as $headerKey => $sqlColKey) {
959 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
960 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
967 * @param int $contactId
968 * @param array $exportParams
972 public static function _replaceMergeTokens($contactId, $exportParams) {
973 $greetings = array();
976 $greetingFields = array(
980 foreach ($greetingFields as $greeting) {
981 if (!empty($exportParams[$greeting])) {
982 $greetingLabel = $exportParams[$greeting];
983 if (empty($contact)) {
988 $contact = civicrm_api('contact', 'get', $values);
990 if (!empty($contact['is_error'])) {
993 $contact = $contact['values'][$contact['id']];
996 $tokens = array('contact' => $greetingLabel);
997 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1004 * The function unsets static part of the string, if token is the dynamic part.
1006 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1007 * i.e 'Hello Alan' => converted to => 'Alan'
1009 * @param string $parsedString
1010 * @param string $defaultGreeting
1011 * @param bool $addressMergeGreetings
1012 * @param string $greetingType
1016 public static function _trimNonTokens(
1017 &$parsedString, $defaultGreeting,
1018 $addressMergeGreetings, $greetingType = 'postal_greeting'
1020 if (!empty($addressMergeGreetings[$greetingType])) {
1021 $greetingLabel = $addressMergeGreetings[$greetingType];
1023 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1025 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1026 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1027 foreach ($stringsToBeReplaced as $key => $string) {
1028 // to keep one space
1029 $stringsToBeReplaced[$key] = ltrim($string);
1031 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1033 return $parsedString;
1038 * @param array $exportParams
1039 * @param bool $sharedAddress
1043 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1044 static $contactGreetingTokens = array();
1046 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1047 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1049 $merge = $parents = array();
1050 $dao = CRM_Core_DAO
::executeQuery($sql);
1052 while ($dao->fetch()) {
1053 $masterID = $dao->master_id
;
1054 $copyID = $dao->copy_id
;
1055 $masterPostalGreeting = $dao->master_postal_greeting
;
1056 $masterAddressee = $dao->master_addressee
;
1057 $copyAddressee = $dao->copy_addressee
;
1059 if (!$sharedAddress) {
1060 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1061 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1063 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1064 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1066 $masterAddressee = CRM_Utils_Array
::value('addressee',
1067 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1070 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1071 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1073 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1074 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1076 $copyAddressee = CRM_Utils_Array
::value('addressee',
1077 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1081 if (!isset($merge[$masterID])) {
1082 // check if this is an intermediate child
1083 // this happens if there are 3 or more matches a,b, c
1084 // the above query will return a, b / a, c / b, c
1085 // we might be doing a bit more work, but for now its ok, unless someone
1086 // knows how to fix the query above
1087 if (isset($parents[$masterID])) {
1088 $masterID = $parents[$masterID];
1091 $merge[$masterID] = array(
1092 'addressee' => $masterAddressee,
1094 'postalGreeting' => $masterPostalGreeting,
1096 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1099 $parents[$copyID] = $masterID;
1101 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1103 if (!empty($exportParams['postal_greeting_other']) &&
1104 count($merge[$masterID]['copy']) >= 1
1106 // use static greetings specified if no of contacts > 2
1107 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1109 elseif ($copyPostalGreeting) {
1110 self
::_trimNonTokens($copyPostalGreeting,
1111 $postalOptions[$dao->copy_postal_greeting_id
],
1114 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1115 // if there happens to be a duplicate, remove it
1116 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1119 if (!empty($exportParams['addressee_other']) &&
1120 count($merge[$masterID]['copy']) >= 1
1122 // use static greetings specified if no of contacts > 2
1123 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1125 elseif ($copyAddressee) {
1126 self
::_trimNonTokens($copyAddressee,
1127 $addresseeOptions[$dao->copy_addressee_id
],
1128 $exportParams, 'addressee'
1130 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1133 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1140 * Merge household record into the individual record
1143 * @param string $exportTempTable
1144 * Temporary temp table that stores the records.
1145 * @param array $sqlColumns
1146 * Array of names of the table columns of the temp table.
1147 * @param string $prefix
1148 * Name of the relationship type that is prefixed to the table columns.
1150 public static function mergeSameHousehold($exportTempTable, &$sqlColumns, $prefix) {
1151 $prefixColumn = $prefix . '_';
1152 $allKeys = array_keys($sqlColumns);
1153 $replaced = array();
1155 // name map of the non standard fields in header rows & sql columns
1156 $mappingFields = array(
1157 'civicrm_primary_id' => 'id',
1158 'contact_source' => 'source',
1159 'current_employer_id' => 'employer_id',
1160 'contact_is_deleted' => 'is_deleted',
1161 'name' => 'address_name',
1162 'provider_id' => 'im_service_provider',
1163 'phone_type_id' => 'phone_type',
1166 //figure out which columns are to be replaced by which ones
1167 foreach ($sqlColumns as $columnNames => $dontCare) {
1168 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1169 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1172 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1174 if (!empty($sqlColumns[$householdColName])) {
1175 $replaced[$columnNames] = $householdColName;
1179 $query = "UPDATE $exportTempTable SET ";
1182 foreach ($replaced as $from => $to) {
1183 $clause[] = "$from = $to ";
1184 unset($sqlColumns[$to]);
1186 $query .= implode(",\n", $clause);
1187 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1189 CRM_Core_DAO
::executeQuery($query);
1191 //drop the table columns that store redundant household info
1192 $dropQuery = "ALTER TABLE $exportTempTable ";
1193 foreach ($replaced as $householdColumns) {
1194 $dropClause[] = " DROP $householdColumns ";
1196 $dropQuery .= implode(",\n", $dropClause);
1198 CRM_Core_DAO
::executeQuery($dropQuery);
1200 // also drop the temp table if exists
1201 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1202 CRM_Core_DAO
::executeQuery($sql);
1204 // clean up duplicate records
1206 CREATE TABLE {$exportTempTable}_temp SELECT *
1207 FROM {$exportTempTable}
1208 GROUP BY civicrm_primary_id ";
1210 CRM_Core_DAO
::executeQuery($query);
1212 $query = "DROP TABLE $exportTempTable";
1213 CRM_Core_DAO
::executeQuery($query);
1215 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1216 CRM_Core_DAO
::executeQuery($query);
1220 * @param $exportTempTable
1221 * @param $headerRows
1222 * @param $sqlColumns
1223 * @param $exportMode
1224 * @param null $saveFile
1225 * @param string $batchItems
1227 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1228 $writeHeader = TRUE;
1230 $limit = self
::EXPORT_ROW_COUNT
;
1232 $query = "SELECT * FROM $exportTempTable";
1235 $limitQuery = $query . "
1236 LIMIT $offset, $limit
1238 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1244 $componentDetails = array();
1245 while ($dao->fetch()) {
1248 foreach ($sqlColumns as $column => $dontCare) {
1249 $row[$column] = $dao->$column;
1251 $componentDetails[] = $row;
1253 if ($exportMode == 'financial') {
1254 $getExportFileName = 'CiviCRM Contribution Search';
1257 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1259 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1266 if ($saveFile && !empty($csvRows)) {
1267 $batchItems .= $csvRows;
1270 $writeHeader = FALSE;
1276 * Manipulate header rows for relationship fields.
1278 * @param $headerRows
1280 public static function manipulateHeaderRows(&$headerRows) {
1281 foreach ($headerRows as & $header) {
1282 $split = explode('-', $header);
1283 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1284 $split[0] = $relationTypeName;
1285 $header = implode('-', $split);
1291 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1292 * or have no street address
1293 * @param $exportTempTable
1294 * @param $headerRows
1295 * @param $sqlColumns
1296 * @param $exportParams
1298 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1299 $whereClause = array();
1301 if (array_key_exists('is_deceased', $sqlColumns)) {
1302 $whereClause[] = 'is_deceased = 1';
1305 if (array_key_exists('do_not_mail', $sqlColumns)) {
1306 $whereClause[] = 'do_not_mail = 1';
1309 if (array_key_exists('street_address', $sqlColumns)) {
1310 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1312 // check for supplemental_address_1
1313 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1314 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1315 'address_options', TRUE, NULL, TRUE
1317 if (!empty($addressOptions['supplemental_address_1'])) {
1318 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1319 // enclose it again, since we are doing an AND in between a set of ORs
1320 $addressWhereClause = "( $addressWhereClause )";
1324 $whereClause[] = $addressWhereClause;
1327 if (!empty($whereClause)) {
1328 $whereClause = implode(' OR ', $whereClause);
1331 FROM $exportTempTable
1332 WHERE {$whereClause}";
1333 CRM_Core_DAO
::singleValueQuery($query);
1336 // unset temporary columns that were added for postal mailing format
1337 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1338 $unsetKeys = array_keys($sqlColumns);
1339 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1340 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1341 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1348 * Build componentPayment fields.
1350 public static function componentPaymentFields() {
1351 static $componentPaymentFields;
1352 if (!isset($componentPaymentFields)) {
1353 $componentPaymentFields = array(
1354 'componentPaymentField_total_amount' => ts('Total Amount'),
1355 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1356 'componentPaymentField_received_date' => ts('Date Received'),
1357 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1358 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1361 return $componentPaymentFields;
1365 * Set the definition for the header rows and sql columns based on the field to output.
1367 * @param string $field
1368 * @param array $headerRows
1369 * @param \CRM_Export_BAO_ExportProcessor $processor
1373 public static function setHeaderRows($field, $headerRows, $processor) {
1375 $queryFields = $processor->getQueryFields();
1376 if (substr($field, -11) == 'campaign_id') {
1377 // @todo - set this correctly in the xml rather than here.
1378 $headerRows[] = ts('Campaign ID');
1380 elseif ($processor->isMergeSameHousehold() && $field === 'id') {
1381 $headerRows[] = ts('Household ID');
1383 elseif (isset($queryFields[$field]['title'])) {
1384 $headerRows[] = $queryFields[$field]['title'];
1386 elseif ($field == 'provider_id') {
1387 // @todo - set this correctly in the xml rather than here.
1388 $headerRows[] = ts('IM Service Provider');
1390 elseif ($processor->isExportPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1391 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1394 $headerRows[] = $field;
1401 * Get the various arrays that we use to structure our output.
1403 * The extraction of these has been moved to a separate function for clarity and so that
1404 * tests can be added - in particular on the $outputHeaders array.
1406 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1407 * as a step on the refactoring path rather than how it should be.
1409 * @param array $returnProperties
1410 * @param \CRM_Export_BAO_ExportProcessor $processor
1413 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1414 * alias for the field generated by BAO_Query object.
1415 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1416 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1417 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1418 * I'm too embarassed to discuss here.
1420 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1421 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1422 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1423 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1424 * - a) the function used is more efficient or
1425 * - b) this code is old & outdated. Submit your answers to circular bin or better
1426 * yet find a way to comment them for posterity.
1428 public static function getExportStructureArrays($returnProperties, $processor) {
1429 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1430 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1431 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1432 $queryFields = $processor->getQueryFields();
1433 foreach ($returnProperties as $key => $value) {
1434 if (($key != 'location' ||
!is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
1435 $outputColumns[$key] = $value;
1436 $headerRows = self
::setHeaderRows($key, $headerRows, $processor);
1437 self
::sqlColumnDefn($processor, $sqlColumns, $key);
1439 elseif ($processor->isRelationshipTypeKey($key)) {
1440 $outputColumns[$key] = $value;
1442 foreach ($value as $relationField => $relationValue) {
1443 // below block is same as primary block (duplicate)
1444 if (isset($queryFields[$relationField]['title'])) {
1445 if ($queryFields[$relationField]['name'] == 'name') {
1446 $headerName = $field . '-' . $relationField;
1449 if ($relationField == 'current_employer') {
1450 $headerName = $field . '-' . 'current_employer';
1453 $headerName = $field . '-' . $queryFields[$relationField]['name'];
1457 if (!$processor->isHouseholdMergeRelationshipTypeKey($field)) {
1458 // Do not add to header row if we are only generating for merge reasons.
1459 $headerRows[] = $headerName;
1462 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1464 elseif ($relationField == 'phone_type_id') {
1465 $headerName = $field . '-' . 'Phone Type';
1466 $headerRows[] = $headerName;
1467 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1469 elseif ($relationField == 'provider_id') {
1470 $headerName = $field . '-' . 'Im Service Provider';
1471 $headerRows[] = $headerName;
1472 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1474 elseif ($relationField == 'state_province_id') {
1475 $headerName = $field . '-' . 'state_province_id';
1476 $headerRows[] = $headerName;
1477 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1479 elseif (is_array($relationValue) && $relationField == 'location') {
1480 // fix header for location type case
1481 foreach ($relationValue as $ltype => $val) {
1482 foreach (array_keys($val) as $fld) {
1483 $type = explode('-', $fld);
1485 $hdr = "{$ltype}-" . $queryFields[$type[0]]['title'];
1487 if (!empty($type[1])) {
1488 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1489 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $type[1]);
1491 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1492 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_IM', 'provider_id', $type[1]);
1495 $headerName = $field . '-' . $hdr;
1496 $headerRows[] = $headerName;
1497 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1502 self
::manipulateHeaderRows($headerRows);
1505 foreach ($value as $locationType => $locationFields) {
1506 foreach (array_keys($locationFields) as $locationFieldName) {
1507 $type = explode('-', $locationFieldName);
1509 $actualDBFieldName = $type[0];
1510 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1511 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1513 if (!empty($type[1])) {
1514 $daoFieldName .= "-" . $type[1];
1515 if ($actualDBFieldName == 'phone') {
1516 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1518 elseif ($actualDBFieldName == 'im') {
1519 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1522 if ($type[0] == 'im_provider') {
1523 // Warning: shame inducing hack.
1524 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1526 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1527 $headerRows = self
::setHeaderRows($outputFieldName, $headerRows, $processor);
1528 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1529 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1530 $metadata[$daoFieldName] = array('context' => 'country');
1532 if ($actualDBFieldName == 'state_province') {
1533 $metadata[$daoFieldName] = array('context' => 'province');
1535 $outputColumns[$daoFieldName] = TRUE;
1540 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1544 * Get the values of linked household contact.
1546 * @param CRM_Core_DAO $relDAO
1547 * @param array $value
1548 * @param string $field
1551 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1552 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1553 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1554 $i18n = CRM_Core_I18n
::singleton();
1555 foreach ($value as $relationField => $relationValue) {
1556 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1557 $fieldValue = $relDAO->$relationField;
1558 if ($relationField == 'phone_type_id') {
1559 $fieldValue = $phoneTypes[$relationValue];
1561 elseif ($relationField == 'provider_id') {
1562 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1565 elseif (is_object($relDAO) && in_array($relationField, array(
1571 //special case for greeting replacement
1572 $fldValue = "{$relationField}_display";
1573 $fieldValue = $relDAO->$fldValue;
1576 elseif (is_object($relDAO) && $relationField == 'state_province') {
1577 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1579 elseif (is_object($relDAO) && $relationField == 'country') {
1580 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1585 $field = $field . '_';
1586 $relPrefix = $field . $relationField;
1588 if (is_object($relDAO) && $relationField == 'id') {
1589 $row[$relPrefix] = $relDAO->contact_id
;
1591 elseif (is_array($relationValue) && $relationField == 'location') {
1592 foreach ($relationValue as $ltype => $val) {
1593 // If the location name has a space in it the we need to handle that. This
1594 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1595 // improve it should be secure in the knowled it will be caught.
1596 $ltype = str_replace(' ', '_', $ltype);
1597 foreach (array_keys($val) as $fld) {
1598 $type = explode('-', $fld);
1599 $fldValue = "{$ltype}-" . $type[0];
1600 if (!empty($type[1])) {
1601 $fldValue .= "-" . $type[1];
1603 // CRM-3157: localise country, region (both have ‘country’ context)
1604 // and state_province (‘province’ context)
1606 case (!is_object($relDAO)):
1607 $row[$field . '_' . $fldValue] = '';
1610 case in_array('country', $type):
1611 case in_array('world_region', $type):
1612 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1613 array('context' => 'country')
1617 case in_array('state_province', $type):
1618 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1619 array('context' => 'province')
1624 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1630 elseif (isset($fieldValue) && $fieldValue != '') {
1631 //check for custom data
1632 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1633 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1636 //normal relationship fields
1637 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1638 switch ($relationField) {
1640 case 'world_region':
1641 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1644 case 'state_province':
1645 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1649 $row[$relPrefix] = $fieldValue;
1655 // if relation field is empty or null
1656 $row[$relPrefix] = '';
1662 * Get the ids that we want to get related contact details for.
1665 * @param int $exportMode
1669 protected static function getIDsForRelatedContact($ids, $exportMode) {
1670 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1673 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1675 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1676 $dao = CRM_Core_DAO
::executeQuery("
1677 SELECT contact_id FROM civicrm_activity_contact
1678 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1679 record_type_id = {$sourceID}
1682 while ($dao->fetch()) {
1683 $relIDs[] = $dao->contact_id
;
1687 $component = self
::exportComponent($exportMode);
1689 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1690 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1693 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1700 * @param \CRM_Export_BAO_ExportProcessor $processor
1701 * @param $componentTable
1702 * @param $returnProperties
1706 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable, $returnProperties) {
1707 $allRelContactArray = $relationQuery = array();
1708 $queryMode = $processor->getQueryMode();
1709 $exportMode = $processor->getExportMode();
1710 foreach (self
::$relationshipTypes as $rel => $dnt) {
1711 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
1712 $allRelContactArray[$rel] = array();
1713 // build Query for each relationship
1714 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1715 NULL, FALSE, FALSE, $queryMode
1717 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
1719 list($id, $direction) = explode('_', $rel, 2);
1720 // identify the relationship direction
1721 $contactA = 'contact_id_a';
1722 $contactB = 'contact_id_b';
1723 if ($direction == 'b_a') {
1724 $contactA = 'contact_id_b';
1725 $contactB = 'contact_id_a';
1727 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1729 $relationshipJoin = $relationshipClause = '';
1730 if (!$selectAll && $componentTable) {
1731 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1733 elseif (!empty($relIDs)) {
1734 $relID = implode(',', $relIDs);
1735 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1738 $relationFrom = " {$relationFrom}
1739 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1740 {$relationshipJoin} ";
1742 //check for active relationship status only
1743 $today = date('Ymd');
1744 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1745 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1746 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
1747 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1748 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
1750 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1751 while ($allRelContactDAO->fetch()) {
1752 //FIX Me: Migrate this to table rather than array
1753 // build the array of all related contacts
1754 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
1756 $allRelContactDAO->free();
1759 return array($relationQuery, $allRelContactArray);
1764 * @param $iterationDAO
1765 * @param $fieldValue
1768 * @param $paymentDetails
1770 * @param \CRM_Export_BAO_ExportProcessor $processor
1774 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor) {
1776 if ($field == 'id') {
1777 return $iterationDAO->contact_id
;
1778 // special case for calculated field
1780 elseif ($field == 'source_contact_id') {
1781 return $iterationDAO->contact_id
;
1783 elseif ($field == 'pledge_balance_amount') {
1784 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1785 // special case for calculated field
1787 elseif ($field == 'pledge_next_pay_amount') {
1788 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1790 elseif (isset($fieldValue) &&
1793 //check for custom data
1794 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1795 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1798 elseif (in_array($field, array(
1803 //special case for greeting replacement
1804 $fldValue = "{$field}_display";
1805 return $iterationDAO->$fldValue;
1808 //normal fields with a touch of CRM-3157
1811 case 'world_region':
1812 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
1814 case 'state_province':
1815 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
1818 case 'preferred_communication_method':
1819 case 'preferred_mail_format':
1820 case 'communication_style':
1821 return $i18n->crm_translate($fieldValue);
1824 if (isset($metadata[$field])) {
1825 // No I don't know why we do it this way & whether we could
1826 // make better use of pseudoConstants.
1827 if (!empty($metadata[$field]['context'])) {
1828 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1830 if (!empty($metadata[$field]['pseudoconstant'])) {
1831 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1832 // call an external function until sure it is not increasing php processing given this
1833 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1834 // That can be next refactor...
1835 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1836 // but I have to reach a stable point....
1837 $varName = $metadata[$field]['pseudoconstant']['var'];
1838 if ($varName === 'imProviders') {
1839 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1841 if ($varName === 'phoneTypes') {
1842 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
1851 elseif ($processor->isExportSpecifiedPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1852 $paymentTableId = $processor->getPaymentTableID();
1853 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1854 $payFieldMapper = array(
1855 'componentPaymentField_total_amount' => 'total_amount',
1856 'componentPaymentField_contribution_status' => 'contribution_status',
1857 'componentPaymentField_payment_instrument' => 'pay_instru',
1858 'componentPaymentField_transaction_id' => 'trxn_id',
1859 'componentPaymentField_received_date' => 'receive_date',
1861 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1864 // if field is empty or null