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.
51 protected static $headOfHouseholdRelationshipKey;
54 * Key representing the head of household in the relationship array.
60 protected static $memberOfHouseholdRelationshipKey;
63 * Key representing the head of household in the relationship array.
65 * e.g. ['8_b_a' => 'Household Member Is', '8_a_b = 'Household Member Of'.....]
69 protected static $relationshipTypes = [];
72 * Get default return property for export based on mode
74 * @param int $exportMode
77 * @return string $property
78 * Default Return property
80 public static function defaultReturnProperty($exportMode) {
81 // hack to add default return property based on export mode
83 if ($exportMode == CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
) {
84 $property = 'contribution_id';
86 elseif ($exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
) {
87 $property = 'participant_id';
89 elseif ($exportMode == CRM_Export_Form_Select
::MEMBER_EXPORT
) {
90 $property = 'membership_id';
92 elseif ($exportMode == CRM_Export_Form_Select
::PLEDGE_EXPORT
) {
93 $property = 'pledge_id';
95 elseif ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
96 $property = 'case_id';
98 elseif ($exportMode == CRM_Export_Form_Select
::GRANT_EXPORT
) {
99 $property = 'grant_id';
101 elseif ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
102 $property = 'activity_id';
108 * Get Export component
110 * @param int $exportMode
113 * @return string $component
114 * CiviCRM Export Component
116 public static function exportComponent($exportMode) {
117 switch ($exportMode) {
118 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
119 $component = 'civicrm_contribution';
122 case CRM_Export_Form_Select
::EVENT_EXPORT
:
123 $component = 'civicrm_participant';
126 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
127 $component = 'civicrm_membership';
130 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
131 $component = 'civicrm_pledge';
134 case CRM_Export_Form_Select
::GRANT_EXPORT
:
135 $component = 'civicrm_grant';
142 * Get Query Group By Clause
143 * @param int $exportMode
145 * @param string $queryMode
147 * @param array $returnProperties
149 * @param object $query
150 * CRM_Contact_BAO_Query
152 * @return string $groupBy
155 public static function getGroupBy($exportMode, $queryMode, $returnProperties, $query) {
157 if (!empty($returnProperties['tags']) ||
!empty($returnProperties['groups']) ||
158 CRM_Utils_Array
::value('notes', $returnProperties) ||
160 ($queryMode & CRM_Contact_BAO_Query
::MODE_CONTACTS
&& $query->_useGroupBy
)
162 $groupBy = "contact_a.id";
165 switch ($exportMode) {
166 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
167 $groupBy = 'civicrm_contribution.id';
168 if (CRM_Contribute_BAO_Query
::isSoftCreditOptionEnabled()) {
169 // especial group by when soft credit columns are included
170 $groupBy = array('contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id');
174 case CRM_Export_Form_Select
::EVENT_EXPORT
:
175 $groupBy = 'civicrm_participant.id';
178 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
179 $groupBy = "civicrm_membership.id";
183 if ($queryMode & CRM_Contact_BAO_Query
::MODE_ACTIVITY
) {
184 $groupBy = "civicrm_activity.id ";
187 if (!empty($groupBy)) {
188 if (!Civi
::settings()->get('searchPrimaryDetailsOnly')) {
189 CRM_Core_DAO
::disableFullGroupByMode();
191 $groupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($query->_select
, $groupBy);
198 * Get the list the export fields.
200 * @param int $selectAll
201 * User preference while export.
204 * @param array $params
205 * Associated array of fields.
206 * @param string $order
208 * @param array $fields
209 * Associated array of fields.
210 * @param array $moreReturnProperties
211 * Additional return fields.
212 * @param int $exportMode
214 * @param string $componentClause
216 * @param string $componentTable
218 * @param bool $mergeSameAddress
219 * Merge records if they have same address.
220 * @param bool $mergeSameHousehold
221 * Merge records if they belong to the same household.
223 * @param array $exportParams
224 * @param string $queryOperator
227 * An array can be requested from within a unit test.
229 * @throws \CRM_Core_Exception
231 public static function exportComponents(
237 $moreReturnProperties = NULL,
238 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
239 $componentClause = NULL,
240 $componentTable = NULL,
241 $mergeSameAddress = FALSE,
242 $mergeSameHousehold = FALSE,
243 $exportParams = array(),
244 $queryOperator = 'AND'
247 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator);
248 $returnProperties = array();
250 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
251 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
252 // without manually testing the export of IM provider still works.
253 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
254 self
::$relationshipTypes = $processor->getRelationshipTypes();
255 //also merge Head of Household
256 self
::$memberOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Household Member of', self
::$relationshipTypes);
257 self
::$headOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Head of Household for', self
::$relationshipTypes);
259 $queryMode = $processor->getQueryMode();
262 //construct return properties
263 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
265 foreach ($fields as $key => $value) {
266 $fieldName = CRM_Utils_Array
::value(1, $value);
271 if ($processor->isRelationshipTypeKey($fieldName) && (!empty($value[2]) ||
!empty($value[4]))) {
272 $returnProperties[$fieldName] = $processor->setRelationshipReturnProperties($value, $fieldName);
274 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
275 $locTypeId = $value[2];
276 if ($fieldName == 'phone') {
277 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
279 elseif ($fieldName == 'im') {
280 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
283 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
287 //hack to fix component fields
288 //revert mix of event_id and title
289 if ($fieldName == 'event_id') {
290 $returnProperties['event_id'] = 1;
293 $returnProperties[$fieldName] = 1;
297 $defaultExportMode = self
::defaultReturnProperty($exportMode);
298 if ($defaultExportMode) {
299 $returnProperties[$defaultExportMode] = 1;
303 $returnProperties = $processor->getDefaultReturnProperties();
305 // @todo - we are working towards this being entirely a property of the processor
306 $processor->setReturnProperties($returnProperties);
307 $paymentTableId = $processor->getPaymentTableID();
309 if ($mergeSameAddress) {
310 //make sure the addressee fields are selected
311 //while using merge same address feature
312 $returnProperties['addressee'] = 1;
313 $returnProperties['postal_greeting'] = 1;
314 $returnProperties['email_greeting'] = 1;
315 $returnProperties['street_name'] = 1;
316 $returnProperties['household_name'] = 1;
317 $returnProperties['street_address'] = 1;
318 $returnProperties['city'] = 1;
319 $returnProperties['state_province'] = 1;
321 // some columns are required for assistance incase they are not already present
322 $exportParams['merge_same_address']['temp_columns'] = array();
323 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
324 foreach ($tempColumns as $column) {
325 if (!array_key_exists($column, $returnProperties)) {
326 $returnProperties[$column] = 1;
327 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
328 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
333 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
334 // If an Additional Group is selected, then all contacts in that group are
335 // added to the export set (filtering out duplicates).
337 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";
338 CRM_Core_DAO
::executeQuery($query);
341 if ($moreReturnProperties) {
343 if (!empty($moreReturnProperties['group'])) {
344 unset($moreReturnProperties['group']);
345 $moreReturnProperties['groups'] = 1;
347 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
350 $exportParams['postal_mailing_export']['temp_columns'] = array();
351 if ($exportParams['exportOption'] == 2 &&
352 isset($exportParams['postal_mailing_export']) &&
353 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
355 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
356 foreach ($postalColumns as $column) {
357 if (!array_key_exists($column, $returnProperties)) {
358 $returnProperties[$column] = 1;
359 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
364 // rectify params to what proximity search expects if there is a value for prox_distance
366 if (!empty($params)) {
367 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
370 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
372 if ($mergeSameHousehold == 1) {
373 if (empty($returnProperties['id'])) {
374 $returnProperties['id'] = 1;
377 foreach ($returnProperties as $key => $value) {
378 if (!$processor->isRelationshipTypeKey($key)) {
379 $returnProperties[self
::$memberOfHouseholdRelationshipKey][$key] = $value;
380 $returnProperties[self
::$headOfHouseholdRelationshipKey][$key] = $value;
384 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['location_type']);
385 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['im_provider']);
386 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['location_type']);
387 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['im_provider']);
390 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode);
392 // make sure the groups stuff is included only if specifically specified
393 // by the fields param (CRM-1969), else we limit the contacts outputted to only
394 // ones that are part of a group
395 if (!empty($returnProperties['groups'])) {
396 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
397 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
398 // total hack for export, CRM-3618
399 $from = str_replace($oldClause,
405 if (!$selectAll && $componentTable) {
406 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
408 elseif ($componentClause) {
410 $where = "WHERE $componentClause";
413 $where .= " AND $componentClause";
417 // CRM-13982 - check if is deleted
418 $excludeTrashed = TRUE;
419 foreach ($params as $value) {
420 if ($value[0] == 'contact_is_deleted') {
421 $excludeTrashed = FALSE;
424 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
427 $where = "WHERE $trashClause";
430 $where .= " AND $trashClause";
433 $queryString = "$select $from $where $having";
435 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
437 $queryString .= $groupBy;
440 // always add contact_a.id to the ORDER clause
441 // so the order is deterministic
443 if (strpos('contact_a.id', $order) === FALSE) {
444 $order .= ", contact_a.id";
447 list($field, $dir) = explode(' ', $order, 2);
448 $field = trim($field);
449 if (!empty($returnProperties[$field])) {
451 $queryString .= " ORDER BY $order";
455 $addPaymentHeader = FALSE;
457 $paymentDetails = array();
458 if ($processor->isExportPaymentFields()) {
460 // get payment related in for event and members
461 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
462 //get all payment headers.
463 // If we haven't selected specific payment fields, load in all the
465 if (!$processor->isExportSpecifiedPaymentFields()) {
466 $paymentHeaders = self
::componentPaymentFields();
467 if (!empty($paymentDetails)) {
468 $addPaymentHeader = TRUE;
471 // If we have selected specific payment fields, leave the payment headers
472 // as an empty array; the headers for each selected field will be added
475 $paymentHeaders = array();
477 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
480 $componentDetails = array();
483 $rowCount = self
::EXPORT_ROW_COUNT
;
485 // we write to temp table often to avoid using too much memory
490 // for CRM-3157 purposes
491 $i18n = CRM_Core_I18n
::singleton();
493 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor);
495 $limitReached = FALSE;
496 while (!$limitReached) {
497 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
498 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
499 // If this is less than our limit by the end of the iteration we do not need to run the query again to
500 // check if some remain.
501 $rowsThisIteration = 0;
503 while ($iterationDAO->fetch()) {
505 $rowsThisIteration++
;
507 $query->convertToPseudoNames($iterationDAO);
509 //first loop through output columns so that we return what is required, and in same order.
510 foreach ($outputColumns as $field => $value) {
512 // add im_provider to $dao object
513 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
514 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
517 //build row values (data)
519 if (property_exists($iterationDAO, $field)) {
520 $fieldValue = $iterationDAO->$field;
521 // to get phone type from phone type id
522 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
523 $fieldValue = $phoneTypes[$fieldValue];
525 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
526 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
528 elseif (strstr($field, 'master_id')) {
529 $masterAddressId = NULL;
530 if (isset($iterationDAO->$field)) {
531 $masterAddressId = $iterationDAO->$field;
533 // get display name of contact that address is shared.
534 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
538 if ($processor->isRelationshipTypeKey($field)) {
539 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
540 $relationQuery[$field]->convertToPseudoNames($relDAO);
541 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
544 $row[$field] = self
::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor);
548 // add payment headers if required
549 if ($addPaymentHeader && $processor->isExportPaymentFields()) {
550 // @todo rather than do this for every single row do it before the loop starts.
551 // where other header definitions take place.
552 $headerRows = array_merge($headerRows, $paymentHeaders);
553 foreach (array_keys($paymentHeaders) as $paymentHdr) {
554 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
559 $exportTempTable = self
::createTempTable($sqlColumns);
562 //build header only once
565 // If specific payment fields have been selected for export, payment
566 // data will already be in $row. Otherwise, add payment related
567 // information, if appropriate.
568 if ($addPaymentHeader) {
569 if (!$processor->isExportSpecifiedPaymentFields()) {
570 if ($processor->isExportPaymentFields()) {
571 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
572 if (!is_array($paymentData) ||
empty($paymentData)) {
573 $paymentData = $nullContributionDetails;
575 $row = array_merge($row, $paymentData);
577 elseif (!empty($paymentDetails)) {
578 $row = array_merge($row, $nullContributionDetails);
582 //remove organization name for individuals if it is set for current employer
583 if (!empty($row['contact_type']) &&
584 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
586 $row['organization_name'] = '';
589 // add component info
590 // write the row to a file
591 $componentDetails[] = $row;
593 // output every $tempRowCount rows
594 if ($count %
$tempRowCount == 0) {
595 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
596 $componentDetails = array();
599 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
600 $limitReached = TRUE;
602 $offset +
= $rowCount;
605 if ($exportTempTable) {
606 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
608 // if postalMailing option is checked, exclude contacts who are deceased, have
609 // "Do not mail" privacy setting, or have no street address
610 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
611 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
613 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
616 // do merge same address and merge same household processing
617 if ($mergeSameAddress) {
618 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
621 // merge the records if they have corresponding households
622 if ($mergeSameHousehold) {
623 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$memberOfHouseholdRelationshipKey);
624 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$headOfHouseholdRelationshipKey);
628 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
630 // In order to be able to write a unit test against this function we need to suppress
631 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
632 if (empty($exportParams['suppress_csv_for_testing'])) {
633 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
636 // return tableName and sqlColumns in test context
637 return array($exportTempTable, $sqlColumns, $headerRows);
640 // delete the export temp table and component table
641 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
642 CRM_Core_DAO
::executeQuery($sql);
643 CRM_Core_DAO
::reenableFullGroupByMode();
644 CRM_Utils_System
::civiExit();
647 CRM_Core_DAO
::reenableFullGroupByMode();
648 throw new CRM_Core_Exception(ts('No records to export'));
653 * Name of the export file based on mode.
655 * @param string $output
663 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
665 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
666 return ts('CiviCRM Contact Search');
668 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
669 return ts('CiviCRM Contribution Search');
671 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
672 return ts('CiviCRM Member Search');
674 case CRM_Export_Form_Select
::EVENT_EXPORT
:
675 return ts('CiviCRM Participant Search');
677 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
678 return ts('CiviCRM Pledge Search');
680 case CRM_Export_Form_Select
::CASE_EXPORT
:
681 return ts('CiviCRM Case Search');
683 case CRM_Export_Form_Select
::GRANT_EXPORT
:
684 return ts('CiviCRM Grant Search');
686 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
687 return ts('CiviCRM Activity Search');
692 * Handle import error file creation.
694 public static function invoke() {
695 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
696 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
697 if (empty($parserName) ||
empty($type)) {
701 // clean and ensure parserName is a valid string
702 $parserName = CRM_Utils_String
::munge($parserName);
703 $parserClass = explode('_', $parserName);
705 // make sure parserClass is in the CRM namespace and
706 // at least 3 levels deep
707 if ($parserClass[0] == 'CRM' &&
708 count($parserClass) >= 3
710 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
711 // ensure the functions exists
712 if (method_exists($parserName, 'errorFileName') &&
713 method_exists($parserName, 'saveFileName')
715 $errorFileName = $parserName::errorFileName($type);
716 $saveFileName = $parserName::saveFileName($type);
717 if (!empty($errorFileName) && !empty($saveFileName)) {
718 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
719 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
720 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
721 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
722 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
724 readfile($errorFileName);
728 CRM_Utils_System
::civiExit();
732 * @param $customSearchClass
736 public static function exportCustom($customSearchClass, $formValues, $order) {
737 $ext = CRM_Extension_System
::singleton()->getMapper();
738 if (!$ext->isExtensionClass($customSearchClass)) {
739 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
742 require_once $ext->classToPath($customSearchClass);
744 $search = new $customSearchClass($formValues);
746 $includeContactIDs = FALSE;
747 if ($formValues['radio_ts'] == 'ts_sel') {
748 $includeContactIDs = TRUE;
751 $sql = $search->all(0, 0, $order, $includeContactIDs);
753 $columns = $search->columns();
755 $header = array_keys($columns);
756 $fields = array_values($columns);
759 $dao = CRM_Core_DAO
::executeQuery($sql);
761 if (method_exists($search, 'alterRow')) {
764 while ($dao->fetch()) {
767 foreach ($fields as $field) {
768 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
769 $row[$field] = $dao->$unqualified_field;
772 $search->alterRow($row);
777 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
778 CRM_Utils_System
::civiExit();
782 * @param \CRM_Export_BAO_ExportProcessor $processor
786 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
787 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
791 $sqlColumns[$processor->getMungedFieldName($field)] = $processor->getSqlColumnDefinition($field);
795 * @param string $tableName
799 public static function writeDetailsToTable($tableName, $details, $sqlColumns) {
800 if (empty($details)) {
809 $id = CRM_Core_DAO
::singleValueQuery($sql);
814 $sqlClause = array();
816 foreach ($details as $row) {
818 $valueString = array($id);
819 foreach ($row as $value) {
821 $valueString[] = "''";
824 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
827 $sqlClause[] = '(' . implode(',', $valueString) . ')';
830 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
832 $sqlValueString = implode(",\n", $sqlClause);
835 INSERT INTO $tableName $sqlColumnString
836 VALUES $sqlValueString
838 CRM_Core_DAO
::executeQuery($sql);
846 public static function createTempTable($sqlColumns) {
847 //creating a temporary table for the search result that need be exported
848 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
850 // also create the sql table
851 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
852 CRM_Core_DAO
::executeQuery($sql);
855 CREATE TABLE {$exportTempTable} (
856 id int unsigned NOT NULL AUTO_INCREMENT,
858 $sql .= implode(",\n", array_values($sqlColumns));
863 // add indexes for street_address and household_name if present
867 'civicrm_primary_id',
870 foreach ($addIndices as $index) {
871 if (isset($sqlColumns[$index])) {
873 INDEX index_{$index}( $index )
879 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
882 CRM_Core_DAO
::executeQuery($sql);
883 return $exportTempTable;
887 * @param string $tableName
890 * @param array $exportParams
892 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
893 // check if any records are present based on if they have used shared address feature,
894 // and not based on if city / state .. matches.
896 SELECT r1.id as copy_id,
897 r1.civicrm_primary_id as copy_contact_id,
898 r1.addressee as copy_addressee,
899 r1.addressee_id as copy_addressee_id,
900 r1.postal_greeting as copy_postal_greeting,
901 r1.postal_greeting_id as copy_postal_greeting_id,
903 r2.civicrm_primary_id as master_contact_id,
904 r2.postal_greeting as master_postal_greeting,
905 r2.postal_greeting_id as master_postal_greeting_id,
906 r2.addressee as master_addressee,
907 r2.addressee_id as master_addressee_id
909 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
910 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
912 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
914 // find all the records that have the same street address BUT not in a household
915 // require match on city and state as well
917 SELECT r1.id as master_id,
918 r1.civicrm_primary_id as master_contact_id,
919 r1.postal_greeting as master_postal_greeting,
920 r1.postal_greeting_id as master_postal_greeting_id,
921 r1.addressee as master_addressee,
922 r1.addressee_id as master_addressee_id,
924 r2.civicrm_primary_id as copy_contact_id,
925 r2.postal_greeting as copy_postal_greeting,
926 r2.postal_greeting_id as copy_postal_greeting_id,
927 r2.addressee as copy_addressee,
928 r2.addressee_id as copy_addressee_id
930 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
931 r1.city = r2.city AND
932 r1.state_province_id = r2.state_province_id )
933 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
934 AND ( r2.household_name IS NULL OR r2.household_name = '' )
935 AND ( r1.street_address != '' )
939 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
941 // unset ids from $merge already present in $linkedMerge
942 foreach ($linkedMerge as $masterID => $values) {
943 $keys = array($masterID);
944 $keys = array_merge($keys, array_keys($values['copy']));
945 foreach ($merge as $mid => $vals) {
946 if (in_array($mid, $keys)) {
950 foreach ($values['copy'] as $copyId) {
951 if (in_array($copyId, $keys)) {
952 unset($merge[$mid]['copy'][$copyId]);
958 $merge = $merge +
$linkedMerge;
960 foreach ($merge as $masterID => $values) {
963 SET addressee = %1, postal_greeting = %2, email_greeting = %3
967 1 => array($values['addressee'], 'String'),
968 2 => array($values['postalGreeting'], 'String'),
969 3 => array($values['emailGreeting'], 'String'),
970 4 => array($masterID, 'Integer'),
972 CRM_Core_DAO
::executeQuery($sql, $params);
975 $deleteIDs = array_keys($values['copy']);
976 $deleteIDString = implode(',', $deleteIDs);
978 DELETE FROM $tableName
979 WHERE id IN ( $deleteIDString )
981 CRM_Core_DAO
::executeQuery($sql);
984 // unset temporary columns that were added for postal mailing format
985 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
986 $unsetKeys = array_keys($sqlColumns);
987 foreach ($unsetKeys as $headerKey => $sqlColKey) {
988 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
989 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
996 * @param int $contactId
997 * @param array $exportParams
1001 public static function _replaceMergeTokens($contactId, $exportParams) {
1002 $greetings = array();
1005 $greetingFields = array(
1009 foreach ($greetingFields as $greeting) {
1010 if (!empty($exportParams[$greeting])) {
1011 $greetingLabel = $exportParams[$greeting];
1012 if (empty($contact)) {
1017 $contact = civicrm_api('contact', 'get', $values);
1019 if (!empty($contact['is_error'])) {
1022 $contact = $contact['values'][$contact['id']];
1025 $tokens = array('contact' => $greetingLabel);
1026 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1033 * The function unsets static part of the string, if token is the dynamic part.
1035 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1036 * i.e 'Hello Alan' => converted to => 'Alan'
1038 * @param string $parsedString
1039 * @param string $defaultGreeting
1040 * @param bool $addressMergeGreetings
1041 * @param string $greetingType
1045 public static function _trimNonTokens(
1046 &$parsedString, $defaultGreeting,
1047 $addressMergeGreetings, $greetingType = 'postal_greeting'
1049 if (!empty($addressMergeGreetings[$greetingType])) {
1050 $greetingLabel = $addressMergeGreetings[$greetingType];
1052 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1054 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1055 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1056 foreach ($stringsToBeReplaced as $key => $string) {
1057 // to keep one space
1058 $stringsToBeReplaced[$key] = ltrim($string);
1060 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1062 return $parsedString;
1067 * @param array $exportParams
1068 * @param bool $sharedAddress
1072 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1073 static $contactGreetingTokens = array();
1075 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1076 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1078 $merge = $parents = array();
1079 $dao = CRM_Core_DAO
::executeQuery($sql);
1081 while ($dao->fetch()) {
1082 $masterID = $dao->master_id
;
1083 $copyID = $dao->copy_id
;
1084 $masterPostalGreeting = $dao->master_postal_greeting
;
1085 $masterAddressee = $dao->master_addressee
;
1086 $copyAddressee = $dao->copy_addressee
;
1088 if (!$sharedAddress) {
1089 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1090 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1092 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1093 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1095 $masterAddressee = CRM_Utils_Array
::value('addressee',
1096 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1099 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1100 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1102 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1103 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1105 $copyAddressee = CRM_Utils_Array
::value('addressee',
1106 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1110 if (!isset($merge[$masterID])) {
1111 // check if this is an intermediate child
1112 // this happens if there are 3 or more matches a,b, c
1113 // the above query will return a, b / a, c / b, c
1114 // we might be doing a bit more work, but for now its ok, unless someone
1115 // knows how to fix the query above
1116 if (isset($parents[$masterID])) {
1117 $masterID = $parents[$masterID];
1120 $merge[$masterID] = array(
1121 'addressee' => $masterAddressee,
1123 'postalGreeting' => $masterPostalGreeting,
1125 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1128 $parents[$copyID] = $masterID;
1130 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1132 if (!empty($exportParams['postal_greeting_other']) &&
1133 count($merge[$masterID]['copy']) >= 1
1135 // use static greetings specified if no of contacts > 2
1136 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1138 elseif ($copyPostalGreeting) {
1139 self
::_trimNonTokens($copyPostalGreeting,
1140 $postalOptions[$dao->copy_postal_greeting_id
],
1143 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1144 // if there happens to be a duplicate, remove it
1145 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1148 if (!empty($exportParams['addressee_other']) &&
1149 count($merge[$masterID]['copy']) >= 1
1151 // use static greetings specified if no of contacts > 2
1152 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1154 elseif ($copyAddressee) {
1155 self
::_trimNonTokens($copyAddressee,
1156 $addresseeOptions[$dao->copy_addressee_id
],
1157 $exportParams, 'addressee'
1159 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1162 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1169 * Merge household record into the individual record
1172 * @param string $exportTempTable
1173 * Temporary temp table that stores the records.
1174 * @param array $headerRows
1175 * Array of headers for the export file.
1176 * @param array $sqlColumns
1177 * Array of names of the table columns of the temp table.
1178 * @param string $prefix
1179 * Name of the relationship type that is prefixed to the table columns.
1181 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1182 $prefixColumn = $prefix . '_';
1183 $allKeys = array_keys($sqlColumns);
1184 $replaced = array();
1185 $headerRows = array_values($headerRows);
1187 // name map of the non standard fields in header rows & sql columns
1188 $mappingFields = array(
1189 'civicrm_primary_id' => 'id',
1190 'contact_source' => 'source',
1191 'current_employer_id' => 'employer_id',
1192 'contact_is_deleted' => 'is_deleted',
1193 'name' => 'address_name',
1194 'provider_id' => 'im_service_provider',
1195 'phone_type_id' => 'phone_type',
1198 //figure out which columns are to be replaced by which ones
1199 foreach ($sqlColumns as $columnNames => $dontCare) {
1200 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1201 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1204 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1206 if (!empty($sqlColumns[$householdColName])) {
1207 $replaced[$columnNames] = $householdColName;
1211 $query = "UPDATE $exportTempTable SET ";
1214 foreach ($replaced as $from => $to) {
1215 $clause[] = "$from = $to ";
1216 unset($sqlColumns[$to]);
1217 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1218 unset($headerRows[$key]);
1221 $query .= implode(",\n", $clause);
1222 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1224 CRM_Core_DAO
::executeQuery($query);
1226 //drop the table columns that store redundant household info
1227 $dropQuery = "ALTER TABLE $exportTempTable ";
1228 foreach ($replaced as $householdColumns) {
1229 $dropClause[] = " DROP $householdColumns ";
1231 $dropQuery .= implode(",\n", $dropClause);
1233 CRM_Core_DAO
::executeQuery($dropQuery);
1235 // also drop the temp table if exists
1236 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1237 CRM_Core_DAO
::executeQuery($sql);
1239 // clean up duplicate records
1241 CREATE TABLE {$exportTempTable}_temp SELECT *
1242 FROM {$exportTempTable}
1243 GROUP BY civicrm_primary_id ";
1245 CRM_Core_DAO
::executeQuery($query);
1247 $query = "DROP TABLE $exportTempTable";
1248 CRM_Core_DAO
::executeQuery($query);
1250 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1251 CRM_Core_DAO
::executeQuery($query);
1255 * @param $exportTempTable
1256 * @param $headerRows
1257 * @param $sqlColumns
1258 * @param $exportMode
1259 * @param null $saveFile
1260 * @param string $batchItems
1262 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1263 $writeHeader = TRUE;
1265 $limit = self
::EXPORT_ROW_COUNT
;
1267 $query = "SELECT * FROM $exportTempTable";
1270 $limitQuery = $query . "
1271 LIMIT $offset, $limit
1273 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1279 $componentDetails = array();
1280 while ($dao->fetch()) {
1283 foreach ($sqlColumns as $column => $dontCare) {
1284 $row[$column] = $dao->$column;
1286 $componentDetails[] = $row;
1288 if ($exportMode == 'financial') {
1289 $getExportFileName = 'CiviCRM Contribution Search';
1292 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1294 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1301 if ($saveFile && !empty($csvRows)) {
1302 $batchItems .= $csvRows;
1305 $writeHeader = FALSE;
1311 * Manipulate header rows for relationship fields.
1313 * @param $headerRows
1315 public static function manipulateHeaderRows(&$headerRows) {
1316 foreach ($headerRows as & $header) {
1317 $split = explode('-', $header);
1318 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1319 $split[0] = $relationTypeName;
1320 $header = implode('-', $split);
1326 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1327 * or have no street address
1328 * @param $exportTempTable
1329 * @param $headerRows
1330 * @param $sqlColumns
1331 * @param $exportParams
1333 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1334 $whereClause = array();
1336 if (array_key_exists('is_deceased', $sqlColumns)) {
1337 $whereClause[] = 'is_deceased = 1';
1340 if (array_key_exists('do_not_mail', $sqlColumns)) {
1341 $whereClause[] = 'do_not_mail = 1';
1344 if (array_key_exists('street_address', $sqlColumns)) {
1345 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1347 // check for supplemental_address_1
1348 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1349 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1350 'address_options', TRUE, NULL, TRUE
1352 if (!empty($addressOptions['supplemental_address_1'])) {
1353 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1354 // enclose it again, since we are doing an AND in between a set of ORs
1355 $addressWhereClause = "( $addressWhereClause )";
1359 $whereClause[] = $addressWhereClause;
1362 if (!empty($whereClause)) {
1363 $whereClause = implode(' OR ', $whereClause);
1366 FROM $exportTempTable
1367 WHERE {$whereClause}";
1368 CRM_Core_DAO
::singleValueQuery($query);
1371 // unset temporary columns that were added for postal mailing format
1372 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1373 $unsetKeys = array_keys($sqlColumns);
1374 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1375 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1376 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1383 * Build componentPayment fields.
1385 public static function componentPaymentFields() {
1386 static $componentPaymentFields;
1387 if (!isset($componentPaymentFields)) {
1388 $componentPaymentFields = array(
1389 'componentPaymentField_total_amount' => ts('Total Amount'),
1390 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1391 'componentPaymentField_received_date' => ts('Date Received'),
1392 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1393 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1396 return $componentPaymentFields;
1400 * Set the definition for the header rows and sql columns based on the field to output.
1402 * @param string $field
1403 * @param array $headerRows
1404 * @param array $sqlColumns
1405 * Columns to go in the temp table.
1406 * @param \CRM_Export_BAO_ExportProcessor $processor
1407 * @param array|string $value
1408 * @param array $phoneTypes
1409 * @param array $imProviders
1413 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders) {
1415 $queryFields = $processor->getQueryFields();
1416 if (substr($field, -11) == 'campaign_id') {
1417 // @todo - set this correctly in the xml rather than here.
1418 $headerRows[] = ts('Campaign ID');
1420 elseif (isset($queryFields[$field]['title'])) {
1421 $headerRows[] = $queryFields[$field]['title'];
1423 elseif ($field == 'provider_id') {
1424 // @todo - set this correctly in the xml rather than here.
1425 $headerRows[] = ts('IM Service Provider');
1427 elseif ($processor->isRelationshipTypeKey($field)) {
1428 foreach ($value as $relationField => $relationValue) {
1429 // below block is same as primary block (duplicate)
1430 if (isset($queryFields[$relationField]['title'])) {
1431 if ($queryFields[$relationField]['name'] == 'name') {
1432 $headerName = $field . '-' . $relationField;
1435 if ($relationField == 'current_employer') {
1436 $headerName = $field . '-' . 'current_employer';
1439 $headerName = $field . '-' . $queryFields[$relationField]['name'];
1443 $headerRows[] = $headerName;
1445 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1447 elseif ($relationField == 'phone_type_id') {
1448 $headerName = $field . '-' . 'Phone Type';
1449 $headerRows[] = $headerName;
1450 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1452 elseif ($relationField == 'provider_id') {
1453 $headerName = $field . '-' . 'Im Service Provider';
1454 $headerRows[] = $headerName;
1455 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1457 elseif ($relationField == 'state_province_id') {
1458 $headerName = $field . '-' . 'state_province_id';
1459 $headerRows[] = $headerName;
1460 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1462 elseif (is_array($relationValue) && $relationField == 'location') {
1463 // fix header for location type case
1464 foreach ($relationValue as $ltype => $val) {
1465 foreach (array_keys($val) as $fld) {
1466 $type = explode('-', $fld);
1468 $hdr = "{$ltype}-" . $queryFields[$type[0]]['title'];
1470 if (!empty($type[1])) {
1471 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1472 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1474 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1475 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1478 $headerName = $field . '-' . $hdr;
1479 $headerRows[] = $headerName;
1480 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1485 self
::manipulateHeaderRows($headerRows);
1487 elseif ($processor->isExportPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1488 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1491 $headerRows[] = $field;
1494 self
::sqlColumnDefn($processor, $sqlColumns, $field);
1496 return array($headerRows, $sqlColumns);
1500 * Get the various arrays that we use to structure our output.
1502 * The extraction of these has been moved to a separate function for clarity and so that
1503 * tests can be added - in particular on the $outputHeaders array.
1505 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1506 * as a step on the refactoring path rather than how it should be.
1508 * @param array $returnProperties
1509 * @param \CRM_Export_BAO_ExportProcessor $processor
1512 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1513 * alias for the field generated by BAO_Query object.
1514 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1515 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1516 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1517 * I'm too embarassed to discuss here.
1519 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1520 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1521 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1522 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1523 * - a) the function used is more efficient or
1524 * - b) this code is old & outdated. Submit your answers to circular bin or better
1525 * yet find a way to comment them for posterity.
1527 public static function getExportStructureArrays($returnProperties, $processor) {
1528 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1529 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1530 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1532 $queryFields = $processor->getQueryFields();
1533 foreach ($returnProperties as $key => $value) {
1534 if ($key != 'location' ||
!is_array($value)) {
1535 $outputColumns[$key] = $value;
1536 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders);
1539 foreach ($value as $locationType => $locationFields) {
1540 foreach (array_keys($locationFields) as $locationFieldName) {
1541 $type = explode('-', $locationFieldName);
1543 $actualDBFieldName = $type[0];
1544 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1545 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1547 if (!empty($type[1])) {
1548 $daoFieldName .= "-" . $type[1];
1549 if ($actualDBFieldName == 'phone') {
1550 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1552 elseif ($actualDBFieldName == 'im') {
1553 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1556 if ($type[0] == 'im_provider') {
1557 // Warning: shame inducing hack.
1558 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1560 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1561 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders);
1562 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1563 $metadata[$daoFieldName] = array('context' => 'country');
1565 if ($actualDBFieldName == 'state_province') {
1566 $metadata[$daoFieldName] = array('context' => 'province');
1568 $outputColumns[$daoFieldName] = TRUE;
1573 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1577 * Get the values of linked household contact.
1579 * @param CRM_Core_DAO $relDAO
1580 * @param array $value
1581 * @param string $field
1584 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1585 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1586 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1587 $i18n = CRM_Core_I18n
::singleton();
1588 foreach ($value as $relationField => $relationValue) {
1589 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1590 $fieldValue = $relDAO->$relationField;
1591 if ($relationField == 'phone_type_id') {
1592 $fieldValue = $phoneTypes[$relationValue];
1594 elseif ($relationField == 'provider_id') {
1595 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1598 elseif (is_object($relDAO) && in_array($relationField, array(
1604 //special case for greeting replacement
1605 $fldValue = "{$relationField}_display";
1606 $fieldValue = $relDAO->$fldValue;
1609 elseif (is_object($relDAO) && $relationField == 'state_province') {
1610 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1612 elseif (is_object($relDAO) && $relationField == 'country') {
1613 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1618 $field = $field . '_';
1619 $relPrefix = $field . $relationField;
1621 if (is_object($relDAO) && $relationField == 'id') {
1622 $row[$relPrefix] = $relDAO->contact_id
;
1624 elseif (is_array($relationValue) && $relationField == 'location') {
1625 foreach ($relationValue as $ltype => $val) {
1626 foreach (array_keys($val) as $fld) {
1627 $type = explode('-', $fld);
1628 $fldValue = "{$ltype}-" . $type[0];
1629 if (!empty($type[1])) {
1630 $fldValue .= "-" . $type[1];
1632 // CRM-3157: localise country, region (both have ‘country’ context)
1633 // and state_province (‘province’ context)
1635 case (!is_object($relDAO)):
1636 $row[$field . '_' . $fldValue] = '';
1639 case in_array('country', $type):
1640 case in_array('world_region', $type):
1641 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1642 array('context' => 'country')
1646 case in_array('state_province', $type):
1647 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1648 array('context' => 'province')
1653 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1659 elseif (isset($fieldValue) && $fieldValue != '') {
1660 //check for custom data
1661 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1662 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1665 //normal relationship fields
1666 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1667 switch ($relationField) {
1669 case 'world_region':
1670 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1673 case 'state_province':
1674 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1678 $row[$relPrefix] = $fieldValue;
1684 // if relation field is empty or null
1685 $row[$relPrefix] = '';
1691 * Get the ids that we want to get related contact details for.
1694 * @param int $exportMode
1698 protected static function getIDsForRelatedContact($ids, $exportMode) {
1699 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1702 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1704 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1705 $dao = CRM_Core_DAO
::executeQuery("
1706 SELECT contact_id FROM civicrm_activity_contact
1707 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1708 record_type_id = {$sourceID}
1711 while ($dao->fetch()) {
1712 $relIDs[] = $dao->contact_id
;
1716 $component = self
::exportComponent($exportMode);
1718 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1719 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1722 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1729 * @param $exportMode
1730 * @param $componentTable
1731 * @param $returnProperties
1735 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode) {
1736 $allRelContactArray = $relationQuery = array();
1738 foreach (self
::$relationshipTypes as $rel => $dnt) {
1739 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
1740 $allRelContactArray[$rel] = array();
1741 // build Query for each relationship
1742 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1743 NULL, FALSE, FALSE, $queryMode
1745 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
1747 list($id, $direction) = explode('_', $rel, 2);
1748 // identify the relationship direction
1749 $contactA = 'contact_id_a';
1750 $contactB = 'contact_id_b';
1751 if ($direction == 'b_a') {
1752 $contactA = 'contact_id_b';
1753 $contactB = 'contact_id_a';
1755 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1757 $relationshipJoin = $relationshipClause = '';
1758 if (!$selectAll && $componentTable) {
1759 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1761 elseif (!empty($relIDs)) {
1762 $relID = implode(',', $relIDs);
1763 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1766 $relationFrom = " {$relationFrom}
1767 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1768 {$relationshipJoin} ";
1770 //check for active relationship status only
1771 $today = date('Ymd');
1772 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1773 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1774 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
1775 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1776 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
1778 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1779 while ($allRelContactDAO->fetch()) {
1780 //FIX Me: Migrate this to table rather than array
1781 // build the array of all related contacts
1782 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
1784 $allRelContactDAO->free();
1787 return array($relationQuery, $allRelContactArray);
1792 * @param $iterationDAO
1793 * @param $fieldValue
1796 * @param $paymentDetails
1798 * @param \CRM_Export_BAO_ExportProcessor $processor
1802 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $paymentDetails, $processor) {
1804 if ($field == 'id') {
1805 return $iterationDAO->contact_id
;
1806 // special case for calculated field
1808 elseif ($field == 'source_contact_id') {
1809 return $iterationDAO->contact_id
;
1811 elseif ($field == 'pledge_balance_amount') {
1812 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1813 // special case for calculated field
1815 elseif ($field == 'pledge_next_pay_amount') {
1816 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1818 elseif (isset($fieldValue) &&
1821 //check for custom data
1822 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1823 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1826 elseif (in_array($field, array(
1831 //special case for greeting replacement
1832 $fldValue = "{$field}_display";
1833 return $iterationDAO->$fldValue;
1836 //normal fields with a touch of CRM-3157
1839 case 'world_region':
1840 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
1842 case 'state_province':
1843 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
1846 case 'preferred_communication_method':
1847 case 'preferred_mail_format':
1848 case 'communication_style':
1849 return $i18n->crm_translate($fieldValue);
1852 if (isset($metadata[$field])) {
1853 // No I don't know why we do it this way & whether we could
1854 // make better use of pseudoConstants.
1855 if (!empty($metadata[$field]['context'])) {
1856 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1858 if (!empty($metadata[$field]['pseudoconstant'])) {
1859 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1860 // call an external function until sure it is not increasing php processing given this
1861 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1862 // That can be next refactor...
1863 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1864 // but I have to reach a stable point....
1865 $varName = $metadata[$field]['pseudoconstant']['var'];
1866 if ($varName === 'imProviders') {
1867 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1869 if ($varName === 'phoneTypes') {
1870 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
1879 elseif ($processor->isExportSpecifiedPaymentFields() && array_key_exists($field, self
::componentPaymentFields())) {
1880 $paymentTableId = $processor->getPaymentTableID();
1881 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
1882 $payFieldMapper = array(
1883 'componentPaymentField_total_amount' => 'total_amount',
1884 'componentPaymentField_contribution_status' => 'contribution_status',
1885 'componentPaymentField_payment_instrument' => 'pay_instru',
1886 'componentPaymentField_transaction_id' => 'trxn_id',
1887 'componentPaymentField_received_date' => 'receive_date',
1889 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
1892 // if field is empty or null