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 //construct return properties
242 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
244 foreach ($fields as $key => $value) {
245 $fieldName = CRM_Utils_Array
::value(1, $value);
250 if ($processor->isRelationshipTypeKey($fieldName) && (!empty($value[2]) ||
!empty($value[4]))) {
251 $returnProperties[$fieldName] = $processor->setRelationshipReturnProperties($value, $fieldName);
253 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
254 $locTypeId = $value[2];
255 if ($fieldName == 'phone') {
256 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
258 elseif ($fieldName == 'im') {
259 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
262 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
266 //hack to fix component fields
267 //revert mix of event_id and title
268 if ($fieldName == 'event_id') {
269 $returnProperties['event_id'] = 1;
272 $returnProperties[$fieldName] = 1;
276 $defaultExportMode = self
::defaultReturnProperty($exportMode);
277 if ($defaultExportMode) {
278 $returnProperties[$defaultExportMode] = 1;
282 $returnProperties = $processor->getDefaultReturnProperties();
284 // @todo - we are working towards this being entirely a property of the processor
285 $processor->setReturnProperties($returnProperties);
286 $paymentTableId = $processor->getPaymentTableID();
288 if ($mergeSameAddress) {
289 //make sure the addressee fields are selected
290 //while using merge same address feature
291 $returnProperties['addressee'] = 1;
292 $returnProperties['postal_greeting'] = 1;
293 $returnProperties['email_greeting'] = 1;
294 $returnProperties['street_name'] = 1;
295 $returnProperties['household_name'] = 1;
296 $returnProperties['street_address'] = 1;
297 $returnProperties['city'] = 1;
298 $returnProperties['state_province'] = 1;
300 // some columns are required for assistance incase they are not already present
301 $exportParams['merge_same_address']['temp_columns'] = array();
302 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
303 foreach ($tempColumns as $column) {
304 if (!array_key_exists($column, $returnProperties)) {
305 $returnProperties[$column] = 1;
306 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
307 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
312 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
313 // If an Additional Group is selected, then all contacts in that group are
314 // added to the export set (filtering out duplicates).
316 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";
317 CRM_Core_DAO
::executeQuery($query);
320 if ($moreReturnProperties) {
322 if (!empty($moreReturnProperties['group'])) {
323 unset($moreReturnProperties['group']);
324 $moreReturnProperties['groups'] = 1;
326 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
329 $exportParams['postal_mailing_export']['temp_columns'] = array();
330 if ($exportParams['exportOption'] == 2 &&
331 isset($exportParams['postal_mailing_export']) &&
332 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
334 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
335 foreach ($postalColumns as $column) {
336 if (!array_key_exists($column, $returnProperties)) {
337 $returnProperties[$column] = 1;
338 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
343 // rectify params to what proximity search expects if there is a value for prox_distance
345 if (!empty($params)) {
346 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
349 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
351 if ($mergeSameHousehold == 1) {
352 if (empty($returnProperties['id'])) {
353 $returnProperties['id'] = 1;
356 foreach ($returnProperties as $key => $value) {
357 if (!$processor->isRelationshipTypeKey($key)) {
358 foreach ($processor->getHouseholdRelationshipTypes() as $householdRelationshipType) {
359 if (!in_array($key, ['location_type', 'im_provider'])) {
360 $returnProperties[$householdRelationshipType][$key] = $value;
367 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable, $returnProperties);
369 // make sure the groups stuff is included only if specifically specified
370 // by the fields param (CRM-1969), else we limit the contacts outputted to only
371 // ones that are part of a group
372 if (!empty($returnProperties['groups'])) {
373 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
374 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
375 // total hack for export, CRM-3618
376 $from = str_replace($oldClause,
382 if (!$selectAll && $componentTable) {
383 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
385 elseif ($componentClause) {
387 $where = "WHERE $componentClause";
390 $where .= " AND $componentClause";
394 // CRM-13982 - check if is deleted
395 $excludeTrashed = TRUE;
396 foreach ($params as $value) {
397 if ($value[0] == 'contact_is_deleted') {
398 $excludeTrashed = FALSE;
401 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
404 $where = "WHERE $trashClause";
407 $where .= " AND $trashClause";
410 $queryString = "$select $from $where $having";
412 $groupBy = self
::getGroupBy($processor, $returnProperties, $query);
414 $queryString .= $groupBy;
417 // always add contact_a.id to the ORDER clause
418 // so the order is deterministic
420 if (strpos('contact_a.id', $order) === FALSE) {
421 $order .= ", contact_a.id";
424 list($field, $dir) = explode(' ', $order, 2);
425 $field = trim($field);
426 if (!empty($returnProperties[$field])) {
428 $queryString .= " ORDER BY $order";
432 $addPaymentHeader = FALSE;
434 $paymentDetails = array();
435 if ($processor->isExportPaymentFields()) {
437 // get payment related in for event and members
438 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
439 //get all payment headers.
440 // If we haven't selected specific payment fields, load in all the
442 if (!$processor->isExportSpecifiedPaymentFields()) {
443 $paymentHeaders = self
::componentPaymentFields();
444 if (!empty($paymentDetails)) {
445 $addPaymentHeader = TRUE;
448 // If we have selected specific payment fields, leave the payment headers
449 // as an empty array; the headers for each selected field will be added
452 $paymentHeaders = array();
454 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
457 $componentDetails = array();
460 $rowCount = self
::EXPORT_ROW_COUNT
;
462 // we write to temp table often to avoid using too much memory
467 // for CRM-3157 purposes
468 $i18n = CRM_Core_I18n
::singleton();
470 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
472 $limitReached = FALSE;
473 while (!$limitReached) {
474 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
475 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
476 // If this is less than our limit by the end of the iteration we do not need to run the query again to
477 // check if some remain.
478 $rowsThisIteration = 0;
480 while ($iterationDAO->fetch()) {
482 $rowsThisIteration++
;
484 $query->convertToPseudoNames($iterationDAO);
486 //first loop through output columns so that we return what is required, and in same order.
487 foreach ($outputColumns as $field => $value) {
489 // add im_provider to $dao object
490 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
491 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
494 //build row values (data)
496 if (property_exists($iterationDAO, $field)) {
497 $fieldValue = $iterationDAO->$field;
498 // to get phone type from phone type id
499 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
500 $fieldValue = $phoneTypes[$fieldValue];
502 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
503 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
505 elseif (strstr($field, 'master_id')) {
506 $masterAddressId = NULL;
507 if (isset($iterationDAO->$field)) {
508 $masterAddressId = $iterationDAO->$field;
510 // get display name of contact that address is shared.
511 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
515 if ($processor->isRelationshipTypeKey($field)) {
516 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
517 $relationQuery[$field]->convertToPseudoNames($relDAO);
518 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
521 $row[$field] = self
::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor);
525 // add payment headers if required
526 if ($addPaymentHeader && $processor->isExportPaymentFields()) {
527 // @todo rather than do this for every single row do it before the loop starts.
528 // where other header definitions take place.
529 $headerRows = array_merge($headerRows, $paymentHeaders);
530 foreach (array_keys($paymentHeaders) as $paymentHdr) {
531 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
536 $exportTempTable = self
::createTempTable($sqlColumns);
539 //build header only once
542 // If specific payment fields have been selected for export, payment
543 // data will already be in $row. Otherwise, add payment related
544 // information, if appropriate.
545 if ($addPaymentHeader) {
546 if (!$processor->isExportSpecifiedPaymentFields()) {
547 if ($processor->isExportPaymentFields()) {
548 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
549 if (!is_array($paymentData) ||
empty($paymentData)) {
550 $paymentData = $nullContributionDetails;
552 $row = array_merge($row, $paymentData);
554 elseif (!empty($paymentDetails)) {
555 $row = array_merge($row, $nullContributionDetails);
559 //remove organization name for individuals if it is set for current employer
560 if (!empty($row['contact_type']) &&
561 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
563 $row['organization_name'] = '';
566 // add component info
567 // write the row to a file
568 $componentDetails[] = $row;
570 // output every $tempRowCount rows
571 if ($count %
$tempRowCount == 0) {
572 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
573 $componentDetails = array();
576 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
577 $limitReached = TRUE;
579 $offset +
= $rowCount;
582 if ($exportTempTable) {
583 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
585 // if postalMailing option is checked, exclude contacts who are deceased, have
586 // "Do not mail" privacy setting, or have no street address
587 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
588 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
590 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
593 // do merge same address and merge same household processing
594 if ($mergeSameAddress) {
595 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
598 // merge the records if they have corresponding households
599 if ($mergeSameHousehold) {
600 foreach ($processor->getHouseholdRelationshipTypes() as $householdRelationshipType) {
601 self
::mergeSameHousehold($exportTempTable, $sqlColumns, $householdRelationshipType);
606 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
608 // In order to be able to write a unit test against this function we need to suppress
609 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
610 if (empty($exportParams['suppress_csv_for_testing'])) {
611 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
614 // return tableName sqlColumns headerRows in test context
615 return array($exportTempTable, $sqlColumns, $headerRows);
618 // delete the export temp table and component table
619 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
620 CRM_Core_DAO
::executeQuery($sql);
621 CRM_Core_DAO
::reenableFullGroupByMode();
622 CRM_Utils_System
::civiExit();
625 CRM_Core_DAO
::reenableFullGroupByMode();
626 throw new CRM_Core_Exception(ts('No records to export'));
631 * Name of the export file based on mode.
633 * @param string $output
641 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
643 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
644 return ts('CiviCRM Contact Search');
646 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
647 return ts('CiviCRM Contribution Search');
649 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
650 return ts('CiviCRM Member Search');
652 case CRM_Export_Form_Select
::EVENT_EXPORT
:
653 return ts('CiviCRM Participant Search');
655 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
656 return ts('CiviCRM Pledge Search');
658 case CRM_Export_Form_Select
::CASE_EXPORT
:
659 return ts('CiviCRM Case Search');
661 case CRM_Export_Form_Select
::GRANT_EXPORT
:
662 return ts('CiviCRM Grant Search');
664 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
665 return ts('CiviCRM Activity Search');
670 * Handle import error file creation.
672 public static function invoke() {
673 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
674 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
675 if (empty($parserName) ||
empty($type)) {
679 // clean and ensure parserName is a valid string
680 $parserName = CRM_Utils_String
::munge($parserName);
681 $parserClass = explode('_', $parserName);
683 // make sure parserClass is in the CRM namespace and
684 // at least 3 levels deep
685 if ($parserClass[0] == 'CRM' &&
686 count($parserClass) >= 3
688 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
689 // ensure the functions exists
690 if (method_exists($parserName, 'errorFileName') &&
691 method_exists($parserName, 'saveFileName')
693 $errorFileName = $parserName::errorFileName($type);
694 $saveFileName = $parserName::saveFileName($type);
695 if (!empty($errorFileName) && !empty($saveFileName)) {
696 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
697 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
698 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
699 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
700 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
702 readfile($errorFileName);
706 CRM_Utils_System
::civiExit();
710 * @param $customSearchClass
714 public static function exportCustom($customSearchClass, $formValues, $order) {
715 $ext = CRM_Extension_System
::singleton()->getMapper();
716 if (!$ext->isExtensionClass($customSearchClass)) {
717 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
720 require_once $ext->classToPath($customSearchClass);
722 $search = new $customSearchClass($formValues);
724 $includeContactIDs = FALSE;
725 if ($formValues['radio_ts'] == 'ts_sel') {
726 $includeContactIDs = TRUE;
729 $sql = $search->all(0, 0, $order, $includeContactIDs);
731 $columns = $search->columns();
733 $header = array_keys($columns);
734 $fields = array_values($columns);
737 $dao = CRM_Core_DAO
::executeQuery($sql);
739 if (method_exists($search, 'alterRow')) {
742 while ($dao->fetch()) {
745 foreach ($fields as $field) {
746 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
747 $row[$field] = $dao->$unqualified_field;
750 $search->alterRow($row);
755 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
756 CRM_Utils_System
::civiExit();
760 * @param \CRM_Export_BAO_ExportProcessor $processor
764 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
765 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
769 $sqlColumns[$processor->getMungedFieldName($field)] = $processor->getSqlColumnDefinition($field);
773 * @param string $tableName
777 public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
778 if (empty($details)) {
787 $id = CRM_Core_DAO
::singleValueQuery($sql);
792 $sqlClause = array();
794 foreach ($details as $row) {
796 $valueString = array($id);
797 foreach ($row as $value) {
799 $valueString[] = "''";
802 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
805 $sqlClause[] = '(' . implode(',', $valueString) . ')';
808 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
810 $sqlValueString = implode(",\n", $sqlClause);
813 INSERT INTO $tableName $sqlColumnString
814 VALUES $sqlValueString
816 CRM_Core_DAO
::executeQuery($sql);
824 public static function createTempTable($sqlColumns) {
825 //creating a temporary table for the search result that need be exported
826 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
828 // also create the sql table
829 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
830 CRM_Core_DAO
::executeQuery($sql);
833 CREATE TABLE {$exportTempTable} (
834 id int unsigned NOT NULL AUTO_INCREMENT,
836 $sql .= implode(",\n", array_values($sqlColumns));
841 // add indexes for street_address and household_name if present
845 'civicrm_primary_id',
848 foreach ($addIndices as $index) {
849 if (isset($sqlColumns[$index])) {
851 INDEX index_{$index}( $index )
857 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
860 CRM_Core_DAO
::executeQuery($sql);
861 return $exportTempTable;
865 * @param string $tableName
868 * @param array $exportParams
870 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
871 // check if any records are present based on if they have used shared address feature,
872 // and not based on if city / state .. matches.
874 SELECT r1.id as copy_id,
875 r1.civicrm_primary_id as copy_contact_id,
876 r1.addressee as copy_addressee,
877 r1.addressee_id as copy_addressee_id,
878 r1.postal_greeting as copy_postal_greeting,
879 r1.postal_greeting_id as copy_postal_greeting_id,
881 r2.civicrm_primary_id as master_contact_id,
882 r2.postal_greeting as master_postal_greeting,
883 r2.postal_greeting_id as master_postal_greeting_id,
884 r2.addressee as master_addressee,
885 r2.addressee_id as master_addressee_id
887 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
888 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
890 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
892 // find all the records that have the same street address BUT not in a household
893 // require match on city and state as well
895 SELECT r1.id as master_id,
896 r1.civicrm_primary_id as master_contact_id,
897 r1.postal_greeting as master_postal_greeting,
898 r1.postal_greeting_id as master_postal_greeting_id,
899 r1.addressee as master_addressee,
900 r1.addressee_id as master_addressee_id,
902 r2.civicrm_primary_id as copy_contact_id,
903 r2.postal_greeting as copy_postal_greeting,
904 r2.postal_greeting_id as copy_postal_greeting_id,
905 r2.addressee as copy_addressee,
906 r2.addressee_id as copy_addressee_id
908 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
909 r1.city = r2.city AND
910 r1.state_province_id = r2.state_province_id )
911 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
912 AND ( r2.household_name IS NULL OR r2.household_name = '' )
913 AND ( r1.street_address != '' )
917 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
919 // unset ids from $merge already present in $linkedMerge
920 foreach ($linkedMerge as $masterID => $values) {
921 $keys = array($masterID);
922 $keys = array_merge($keys, array_keys($values['copy']));
923 foreach ($merge as $mid => $vals) {
924 if (in_array($mid, $keys)) {
928 foreach ($values['copy'] as $copyId) {
929 if (in_array($copyId, $keys)) {
930 unset($merge[$mid]['copy'][$copyId]);
936 $merge = $merge +
$linkedMerge;
938 foreach ($merge as $masterID => $values) {
941 SET addressee = %1, postal_greeting = %2, email_greeting = %3
945 1 => array($values['addressee'], 'String'),
946 2 => array($values['postalGreeting'], 'String'),
947 3 => array($values['emailGreeting'], 'String'),
948 4 => array($masterID, 'Integer'),
950 CRM_Core_DAO
::executeQuery($sql, $params);
953 $deleteIDs = array_keys($values['copy']);
954 $deleteIDString = implode(',', $deleteIDs);
956 DELETE FROM $tableName
957 WHERE id IN ( $deleteIDString )
959 CRM_Core_DAO
::executeQuery($sql);
962 // unset temporary columns that were added for postal mailing format
963 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
964 $unsetKeys = array_keys($sqlColumns);
965 foreach ($unsetKeys as $headerKey => $sqlColKey) {
966 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
967 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
974 * @param int $contactId
975 * @param array $exportParams
979 public static function _replaceMergeTokens($contactId, $exportParams) {
980 $greetings = array();
983 $greetingFields = array(
987 foreach ($greetingFields as $greeting) {
988 if (!empty($exportParams[$greeting])) {
989 $greetingLabel = $exportParams[$greeting];
990 if (empty($contact)) {
995 $contact = civicrm_api('contact', 'get', $values);
997 if (!empty($contact['is_error'])) {
1000 $contact = $contact['values'][$contact['id']];
1003 $tokens = array('contact' => $greetingLabel);
1004 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1011 * The function unsets static part of the string, if token is the dynamic part.
1013 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1014 * i.e 'Hello Alan' => converted to => 'Alan'
1016 * @param string $parsedString
1017 * @param string $defaultGreeting
1018 * @param bool $addressMergeGreetings
1019 * @param string $greetingType
1023 public static function _trimNonTokens(
1024 &$parsedString, $defaultGreeting,
1025 $addressMergeGreetings, $greetingType = 'postal_greeting'
1027 if (!empty($addressMergeGreetings[$greetingType])) {
1028 $greetingLabel = $addressMergeGreetings[$greetingType];
1030 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1032 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1033 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1034 foreach ($stringsToBeReplaced as $key => $string) {
1035 // to keep one space
1036 $stringsToBeReplaced[$key] = ltrim($string);
1038 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1040 return $parsedString;
1045 * @param array $exportParams
1046 * @param bool $sharedAddress
1050 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1051 static $contactGreetingTokens = array();
1053 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1054 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1056 $merge = $parents = array();
1057 $dao = CRM_Core_DAO
::executeQuery($sql);
1059 while ($dao->fetch()) {
1060 $masterID = $dao->master_id
;
1061 $copyID = $dao->copy_id
;
1062 $masterPostalGreeting = $dao->master_postal_greeting
;
1063 $masterAddressee = $dao->master_addressee
;
1064 $copyAddressee = $dao->copy_addressee
;
1066 if (!$sharedAddress) {
1067 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1068 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1070 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1071 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1073 $masterAddressee = CRM_Utils_Array
::value('addressee',
1074 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1077 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1078 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1080 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1081 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1083 $copyAddressee = CRM_Utils_Array
::value('addressee',
1084 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1088 if (!isset($merge[$masterID])) {
1089 // check if this is an intermediate child
1090 // this happens if there are 3 or more matches a,b, c
1091 // the above query will return a, b / a, c / b, c
1092 // we might be doing a bit more work, but for now its ok, unless someone
1093 // knows how to fix the query above
1094 if (isset($parents[$masterID])) {
1095 $masterID = $parents[$masterID];
1098 $merge[$masterID] = array(
1099 'addressee' => $masterAddressee,
1101 'postalGreeting' => $masterPostalGreeting,
1103 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1106 $parents[$copyID] = $masterID;
1108 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1110 if (!empty($exportParams['postal_greeting_other']) &&
1111 count($merge[$masterID]['copy']) >= 1
1113 // use static greetings specified if no of contacts > 2
1114 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1116 elseif ($copyPostalGreeting) {
1117 self
::_trimNonTokens($copyPostalGreeting,
1118 $postalOptions[$dao->copy_postal_greeting_id
],
1121 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1122 // if there happens to be a duplicate, remove it
1123 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1126 if (!empty($exportParams['addressee_other']) &&
1127 count($merge[$masterID]['copy']) >= 1
1129 // use static greetings specified if no of contacts > 2
1130 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1132 elseif ($copyAddressee) {
1133 self
::_trimNonTokens($copyAddressee,
1134 $addresseeOptions[$dao->copy_addressee_id
],
1135 $exportParams, 'addressee'
1137 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1140 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1147 * Merge household record into the individual record
1150 * @param string $exportTempTable
1151 * Temporary temp table that stores the records.
1152 * @param array $sqlColumns
1153 * Array of names of the table columns of the temp table.
1154 * @param string $prefix
1155 * Name of the relationship type that is prefixed to the table columns.
1157 public static function mergeSameHousehold($exportTempTable, &$sqlColumns, $prefix) {
1158 $prefixColumn = $prefix . '_';
1159 $allKeys = array_keys($sqlColumns);
1160 $replaced = array();
1162 // name map of the non standard fields in header rows & sql columns
1163 $mappingFields = array(
1164 'civicrm_primary_id' => 'id',
1165 'contact_source' => 'source',
1166 'current_employer_id' => 'employer_id',
1167 'contact_is_deleted' => 'is_deleted',
1168 'name' => 'address_name',
1169 'provider_id' => 'im_service_provider',
1170 'phone_type_id' => 'phone_type',
1173 //figure out which columns are to be replaced by which ones
1174 foreach ($sqlColumns as $columnNames => $dontCare) {
1175 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1176 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1179 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1181 if (!empty($sqlColumns[$householdColName])) {
1182 $replaced[$columnNames] = $householdColName;
1186 $query = "UPDATE $exportTempTable SET ";
1189 foreach ($replaced as $from => $to) {
1190 $clause[] = "$from = $to ";
1191 unset($sqlColumns[$to]);
1193 $query .= implode(",\n", $clause);
1194 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1196 CRM_Core_DAO
::executeQuery($query);
1198 //drop the table columns that store redundant household info
1199 $dropQuery = "ALTER TABLE $exportTempTable ";
1200 foreach ($replaced as $householdColumns) {
1201 $dropClause[] = " DROP $householdColumns ";
1203 $dropQuery .= implode(",\n", $dropClause);
1205 CRM_Core_DAO
::executeQuery($dropQuery);
1207 // also drop the temp table if exists
1208 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1209 CRM_Core_DAO
::executeQuery($sql);
1211 // clean up duplicate records
1213 CREATE TABLE {$exportTempTable}_temp SELECT *
1214 FROM {$exportTempTable}
1215 GROUP BY civicrm_primary_id ";
1217 CRM_Core_DAO
::executeQuery($query);
1219 $query = "DROP TABLE $exportTempTable";
1220 CRM_Core_DAO
::executeQuery($query);
1222 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1223 CRM_Core_DAO
::executeQuery($query);
1227 * @param $exportTempTable
1228 * @param $headerRows
1229 * @param $sqlColumns
1230 * @param $exportMode
1231 * @param null $saveFile
1232 * @param string $batchItems
1234 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1235 $writeHeader = TRUE;
1237 $limit = self
::EXPORT_ROW_COUNT
;
1239 $query = "SELECT * FROM $exportTempTable";
1242 $limitQuery = $query . "
1243 LIMIT $offset, $limit
1245 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1251 $componentDetails = array();
1252 while ($dao->fetch()) {
1255 foreach ($sqlColumns as $column => $dontCare) {
1256 $row[$column] = $dao->$column;
1258 $componentDetails[] = $row;
1260 if ($exportMode == 'financial') {
1261 $getExportFileName = 'CiviCRM Contribution Search';
1264 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1266 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1273 if ($saveFile && !empty($csvRows)) {
1274 $batchItems .= $csvRows;
1277 $writeHeader = FALSE;
1283 * Manipulate header rows for relationship fields.
1285 * @param $headerRows
1287 public static function manipulateHeaderRows(&$headerRows) {
1288 foreach ($headerRows as & $header) {
1289 $split = explode('-', $header);
1290 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1291 $split[0] = $relationTypeName;
1292 $header = implode('-', $split);
1298 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1299 * or have no street address
1300 * @param $exportTempTable
1301 * @param $headerRows
1302 * @param $sqlColumns
1303 * @param $exportParams
1305 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1306 $whereClause = array();
1308 if (array_key_exists('is_deceased', $sqlColumns)) {
1309 $whereClause[] = 'is_deceased = 1';
1312 if (array_key_exists('do_not_mail', $sqlColumns)) {
1313 $whereClause[] = 'do_not_mail = 1';
1316 if (array_key_exists('street_address', $sqlColumns)) {
1317 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1319 // check for supplemental_address_1
1320 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1321 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1322 'address_options', TRUE, NULL, TRUE
1324 if (!empty($addressOptions['supplemental_address_1'])) {
1325 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1326 // enclose it again, since we are doing an AND in between a set of ORs
1327 $addressWhereClause = "( $addressWhereClause )";
1331 $whereClause[] = $addressWhereClause;
1334 if (!empty($whereClause)) {
1335 $whereClause = implode(' OR ', $whereClause);
1338 FROM $exportTempTable
1339 WHERE {$whereClause}";
1340 CRM_Core_DAO
::singleValueQuery($query);
1343 // unset temporary columns that were added for postal mailing format
1344 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1345 $unsetKeys = array_keys($sqlColumns);
1346 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1347 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1348 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1355 * Build componentPayment fields.
1357 public static function componentPaymentFields() {
1358 static $componentPaymentFields;
1359 if (!isset($componentPaymentFields)) {
1360 $componentPaymentFields = array(
1361 'componentPaymentField_total_amount' => ts('Total Amount'),
1362 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1363 'componentPaymentField_received_date' => ts('Date Received'),
1364 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1365 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1368 return $componentPaymentFields;
1372 * Set the definition for the header rows and sql columns based on the field to output.
1374 * @param string $field
1375 * @param array $headerRows
1376 * @param array $sqlColumns
1377 * Columns to go in the temp table.
1378 * @param \CRM_Export_BAO_ExportProcessor $processor
1379 * @param array|string $value
1383 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value) {
1385 $queryFields = $processor->getQueryFields();
1386 if (substr($field, -11) == 'campaign_id') {
1387 // @todo - set this correctly in the xml rather than here.
1388 $headerRows[] = ts('Campaign ID');
1390 elseif ($processor->isMergeSameHousehold() && $field === 'id') {
1391 $headerRows[] = ts('Household ID');
1393 elseif (isset($queryFields[$field]['title'])) {
1394 $headerRows[] = $queryFields[$field]['title'];
1396 elseif ($field == 'provider_id') {
1397 // @todo - set this correctly in the xml rather than here.
1398 $headerRows[] = ts('IM Service Provider');
1400 elseif ($processor->isRelationshipTypeKey($field)) {
1401 foreach ($value as $relationField => $relationValue) {
1402 // below block is same as primary block (duplicate)
1403 if (isset($queryFields[$relationField]['title'])) {
1404 if ($queryFields[$relationField]['name'] == 'name') {
1405 $headerName = $field . '-' . $relationField;
1408 if ($relationField == 'current_employer') {
1409 $headerName = $field . '-' . 'current_employer';
1412 $headerName = $field . '-' . $queryFields[$relationField]['name'];
1416 if (!$processor->isHouseholdMergeRelationshipTypeKey($field)) {
1417 // Do not add to header row if we are only generating for merge reasons.
1418 $headerRows[] = $headerName;
1421 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1423 elseif ($relationField == 'phone_type_id') {
1424 $headerName = $field . '-' . 'Phone Type';
1425 $headerRows[] = $headerName;
1426 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1428 elseif ($relationField == 'provider_id') {
1429 $headerName = $field . '-' . 'Im Service Provider';
1430 $headerRows[] = $headerName;
1431 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1433 elseif ($relationField == 'state_province_id') {
1434 $headerName = $field . '-' . 'state_province_id';
1435 $headerRows[] = $headerName;
1436 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1438 elseif (is_array($relationValue) && $relationField == 'location') {
1439 // fix header for location type case
1440 foreach ($relationValue as $ltype => $val) {
1441 foreach (array_keys($val) as $fld) {
1442 $type = explode('-', $fld);
1444 $hdr = "{$ltype}-" . $queryFields[$type[0]]['title'];
1446 if (!empty($type[1])) {
1447 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1448 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_Phone', 'phone_type_id', $type[1]);
1450 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1451 $hdr .= "-" . CRM_Core_PseudoConstant
::getLabel('CRM_Core_BAO_IM', 'provider_id', $type[1]);
1454 $headerName = $field . '-' . $hdr;
1455 $headerRows[] = $headerName;
1456 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1461 self
::manipulateHeaderRows($headerRows);
1463 elseif ($processor->isExportPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1464 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1467 $headerRows[] = $field;
1470 self
::sqlColumnDefn($processor, $sqlColumns, $field);
1472 return array($headerRows, $sqlColumns);
1476 * Get the various arrays that we use to structure our output.
1478 * The extraction of these has been moved to a separate function for clarity and so that
1479 * tests can be added - in particular on the $outputHeaders array.
1481 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1482 * as a step on the refactoring path rather than how it should be.
1484 * @param array $returnProperties
1485 * @param \CRM_Export_BAO_ExportProcessor $processor
1488 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1489 * alias for the field generated by BAO_Query object.
1490 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1491 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1492 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1493 * I'm too embarassed to discuss here.
1495 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1496 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1497 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1498 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1499 * - a) the function used is more efficient or
1500 * - b) this code is old & outdated. Submit your answers to circular bin or better
1501 * yet find a way to comment them for posterity.
1503 public static function getExportStructureArrays($returnProperties, $processor) {
1504 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1505 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1506 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1507 $queryFields = $processor->getQueryFields();
1508 foreach ($returnProperties as $key => $value) {
1509 if ($key != 'location' ||
!is_array($value)) {
1510 $outputColumns[$key] = $value;
1511 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value);
1514 foreach ($value as $locationType => $locationFields) {
1515 foreach (array_keys($locationFields) as $locationFieldName) {
1516 $type = explode('-', $locationFieldName);
1518 $actualDBFieldName = $type[0];
1519 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1520 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1522 if (!empty($type[1])) {
1523 $daoFieldName .= "-" . $type[1];
1524 if ($actualDBFieldName == 'phone') {
1525 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1527 elseif ($actualDBFieldName == 'im') {
1528 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1531 if ($type[0] == 'im_provider') {
1532 // Warning: shame inducing hack.
1533 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1535 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1536 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value);
1537 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1538 $metadata[$daoFieldName] = array('context' => 'country');
1540 if ($actualDBFieldName == 'state_province') {
1541 $metadata[$daoFieldName] = array('context' => 'province');
1543 $outputColumns[$daoFieldName] = TRUE;
1548 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1552 * Get the values of linked household contact.
1554 * @param CRM_Core_DAO $relDAO
1555 * @param array $value
1556 * @param string $field
1559 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1560 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1561 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1562 $i18n = CRM_Core_I18n
::singleton();
1563 foreach ($value as $relationField => $relationValue) {
1564 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1565 $fieldValue = $relDAO->$relationField;
1566 if ($relationField == 'phone_type_id') {
1567 $fieldValue = $phoneTypes[$relationValue];
1569 elseif ($relationField == 'provider_id') {
1570 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1573 elseif (is_object($relDAO) && in_array($relationField, array(
1579 //special case for greeting replacement
1580 $fldValue = "{$relationField}_display";
1581 $fieldValue = $relDAO->$fldValue;
1584 elseif (is_object($relDAO) && $relationField == 'state_province') {
1585 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1587 elseif (is_object($relDAO) && $relationField == 'country') {
1588 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1593 $field = $field . '_';
1594 $relPrefix = $field . $relationField;
1596 if (is_object($relDAO) && $relationField == 'id') {
1597 $row[$relPrefix] = $relDAO->contact_id
;
1599 elseif (is_array($relationValue) && $relationField == 'location') {
1600 foreach ($relationValue as $ltype => $val) {
1601 foreach (array_keys($val) as $fld) {
1602 $type = explode('-', $fld);
1603 $fldValue = "{$ltype}-" . $type[0];
1604 if (!empty($type[1])) {
1605 $fldValue .= "-" . $type[1];
1607 // CRM-3157: localise country, region (both have ‘country’ context)
1608 // and state_province (‘province’ context)
1610 case (!is_object($relDAO)):
1611 $row[$field . '_' . $fldValue] = '';
1614 case in_array('country', $type):
1615 case in_array('world_region', $type):
1616 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1617 array('context' => 'country')
1621 case in_array('state_province', $type):
1622 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1623 array('context' => 'province')
1628 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1634 elseif (isset($fieldValue) && $fieldValue != '') {
1635 //check for custom data
1636 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1637 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1640 //normal relationship fields
1641 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1642 switch ($relationField) {
1644 case 'world_region':
1645 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1648 case 'state_province':
1649 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1653 $row[$relPrefix] = $fieldValue;
1659 // if relation field is empty or null
1660 $row[$relPrefix] = '';
1666 * Get the ids that we want to get related contact details for.
1669 * @param int $exportMode
1673 protected static function getIDsForRelatedContact($ids, $exportMode) {
1674 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1677 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1679 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1680 $dao = CRM_Core_DAO
::executeQuery("
1681 SELECT contact_id FROM civicrm_activity_contact
1682 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1683 record_type_id = {$sourceID}
1686 while ($dao->fetch()) {
1687 $relIDs[] = $dao->contact_id
;
1691 $component = self
::exportComponent($exportMode);
1693 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1694 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1697 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1704 * @param \CRM_Export_BAO_ExportProcessor $processor
1705 * @param $componentTable
1706 * @param $returnProperties
1710 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable, $returnProperties) {
1711 $allRelContactArray = $relationQuery = array();
1712 $queryMode = $processor->getQueryMode();
1713 $exportMode = $processor->getExportMode();
1714 foreach (self
::$relationshipTypes as $rel => $dnt) {
1715 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
1716 $allRelContactArray[$rel] = array();
1717 // build Query for each relationship
1718 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1719 NULL, FALSE, FALSE, $queryMode
1721 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
1723 list($id, $direction) = explode('_', $rel, 2);
1724 // identify the relationship direction
1725 $contactA = 'contact_id_a';
1726 $contactB = 'contact_id_b';
1727 if ($direction == 'b_a') {
1728 $contactA = 'contact_id_b';
1729 $contactB = 'contact_id_a';
1731 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1733 $relationshipJoin = $relationshipClause = '';
1734 if (!$selectAll && $componentTable) {
1735 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1737 elseif (!empty($relIDs)) {
1738 $relID = implode(',', $relIDs);
1739 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1742 $relationFrom = " {$relationFrom}
1743 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1744 {$relationshipJoin} ";
1746 //check for active relationship status only
1747 $today = date('Ymd');
1748 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1749 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1750 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
1751 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1752 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
1754 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1755 while ($allRelContactDAO->fetch()) {
1756 //FIX Me: Migrate this to table rather than array
1757 // build the array of all related contacts
1758 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
1760 $allRelContactDAO->free();
1763 return array($relationQuery, $allRelContactArray);
1768 * @param $iterationDAO
1769 * @param $fieldValue
1772 * @param $paymentDetails
1774 * @param \CRM_Export_BAO_ExportProcessor $processor
1778 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor) {
1780 if ($field == 'id') {
1781 return $iterationDAO->contact_id
;
1782 // special case for calculated field
1784 elseif ($field == 'source_contact_id') {
1785 return $iterationDAO->contact_id
;
1787 elseif ($field == 'pledge_balance_amount') {
1788 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1789 // special case for calculated field
1791 elseif ($field == 'pledge_next_pay_amount') {
1792 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1794 elseif (isset($fieldValue) &&
1797 //check for custom data
1798 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1799 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1802 elseif (in_array($field, array(
1807 //special case for greeting replacement
1808 $fldValue = "{$field}_display";
1809 return $iterationDAO->$fldValue;
1812 //normal fields with a touch of CRM-3157
1815 case 'world_region':
1816 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
1818 case 'state_province':
1819 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
1822 case 'preferred_communication_method':
1823 case 'preferred_mail_format':
1824 case 'communication_style':
1825 return $i18n->crm_translate($fieldValue);
1828 if (isset($metadata[$field])) {
1829 // No I don't know why we do it this way & whether we could
1830 // make better use of pseudoConstants.
1831 if (!empty($metadata[$field]['context'])) {
1832 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1834 if (!empty($metadata[$field]['pseudoconstant'])) {
1835 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1836 // call an external function until sure it is not increasing php processing given this
1837 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1838 // That can be next refactor...
1839 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1840 // but I have to reach a stable point....
1841 $varName = $metadata[$field]['pseudoconstant']['var'];
1842 if ($varName === 'imProviders') {
1843 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1845 if ($varName === 'phoneTypes') {
1846 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
1855 elseif ($processor->isExportSpecifiedPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1856 $paymentTableId = $processor->getPaymentTableID();
1857 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1858 $payFieldMapper = array(
1859 'componentPaymentField_total_amount' => 'total_amount',
1860 'componentPaymentField_contribution_status' => 'contribution_status',
1861 'componentPaymentField_payment_instrument' => 'pay_instru',
1862 'componentPaymentField_transaction_id' => 'trxn_id',
1863 'componentPaymentField_received_date' => 'receive_date',
1865 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1868 // if field is empty or null