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();
249 $selectedPaymentFields = FALSE;
250 // @todo - this variable is overwritten later - it should be wholly definable in the processor fn.
251 $paymentTableId = $processor->getPaymentTableID();
253 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
254 // Warning - this imProviders var is used in a somewhat fragile way - don't rename it
255 // without manually testing the export of IM provider still works.
256 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
257 self
::$relationshipTypes = $processor->getRelationshipTypes();
258 //also merge Head of Household
259 self
::$memberOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Household Member of', self
::$relationshipTypes);
260 self
::$headOfHouseholdRelationshipKey = CRM_Utils_Array
::key('Head of Household for', self
::$relationshipTypes);
262 $queryMode = $processor->getQueryMode();
265 //construct return properties
266 $locationTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Address', 'location_type_id');
268 foreach ($fields as $key => $value) {
269 $fieldName = CRM_Utils_Array
::value(1, $value);
274 if ($processor->isRelationshipTypeKey($fieldName) && (!empty($value[2]) ||
!empty($value[4]))) {
275 $returnProperties[$fieldName] = $processor->setRelationshipReturnProperties($value, $fieldName);
277 elseif (is_numeric(CRM_Utils_Array
::value(2, $value))) {
278 $locTypeId = $value[2];
279 if ($fieldName == 'phone') {
280 $returnProperties['location'][$locationTypes[$locTypeId]]['phone-' . CRM_Utils_Array
::value(3, $value)] = 1;
282 elseif ($fieldName == 'im') {
283 $returnProperties['location'][$locationTypes[$locTypeId]]['im-' . CRM_Utils_Array
::value(3, $value)] = 1;
286 $returnProperties['location'][$locationTypes[$locTypeId]][$fieldName] = 1;
290 //hack to fix component fields
291 //revert mix of event_id and title
292 if ($fieldName == 'event_id') {
293 $returnProperties['event_id'] = 1;
296 $exportMode == CRM_Export_Form_Select
::EVENT_EXPORT
&&
297 array_key_exists($fieldName, self
::componentPaymentFields())
299 $selectedPaymentFields = TRUE;
300 $paymentTableId = 'participant_id';
301 $returnProperties[$fieldName] = 1;
304 $returnProperties[$fieldName] = 1;
308 $defaultExportMode = self
::defaultReturnProperty($exportMode);
309 if ($defaultExportMode) {
310 $returnProperties[$defaultExportMode] = 1;
314 $returnProperties = $processor->getDefaultReturnProperties();
317 if ($mergeSameAddress) {
318 //make sure the addressee fields are selected
319 //while using merge same address feature
320 $returnProperties['addressee'] = 1;
321 $returnProperties['postal_greeting'] = 1;
322 $returnProperties['email_greeting'] = 1;
323 $returnProperties['street_name'] = 1;
324 $returnProperties['household_name'] = 1;
325 $returnProperties['street_address'] = 1;
326 $returnProperties['city'] = 1;
327 $returnProperties['state_province'] = 1;
329 // some columns are required for assistance incase they are not already present
330 $exportParams['merge_same_address']['temp_columns'] = array();
331 $tempColumns = array('id', 'master_id', 'state_province_id', 'postal_greeting_id', 'addressee_id');
332 foreach ($tempColumns as $column) {
333 if (!array_key_exists($column, $returnProperties)) {
334 $returnProperties[$column] = 1;
335 $column = $column == 'id' ?
'civicrm_primary_id' : $column;
336 $exportParams['merge_same_address']['temp_columns'][$column] = 1;
341 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
342 // If an Additional Group is selected, then all contacts in that group are
343 // added to the export set (filtering out duplicates).
345 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";
346 CRM_Core_DAO
::executeQuery($query);
349 if ($moreReturnProperties) {
351 if (!empty($moreReturnProperties['group'])) {
352 unset($moreReturnProperties['group']);
353 $moreReturnProperties['groups'] = 1;
355 $returnProperties = array_merge($returnProperties, $moreReturnProperties);
358 $exportParams['postal_mailing_export']['temp_columns'] = array();
359 if ($exportParams['exportOption'] == 2 &&
360 isset($exportParams['postal_mailing_export']) &&
361 CRM_Utils_Array
::value('postal_mailing_export', $exportParams['postal_mailing_export']) == 1
363 $postalColumns = array('is_deceased', 'do_not_mail', 'street_address', 'supplemental_address_1');
364 foreach ($postalColumns as $column) {
365 if (!array_key_exists($column, $returnProperties)) {
366 $returnProperties[$column] = 1;
367 $exportParams['postal_mailing_export']['temp_columns'][$column] = 1;
372 // rectify params to what proximity search expects if there is a value for prox_distance
374 if (!empty($params)) {
375 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
378 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order, $returnProperties);
380 if ($mergeSameHousehold == 1) {
381 if (empty($returnProperties['id'])) {
382 $returnProperties['id'] = 1;
385 foreach ($returnProperties as $key => $value) {
386 if (!$processor->isRelationshipTypeKey($key)) {
387 $returnProperties[self
::$memberOfHouseholdRelationshipKey][$key] = $value;
388 $returnProperties[self
::$headOfHouseholdRelationshipKey][$key] = $value;
392 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['location_type']);
393 unset($returnProperties[self
::$memberOfHouseholdRelationshipKey]['im_provider']);
394 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['location_type']);
395 unset($returnProperties[self
::$headOfHouseholdRelationshipKey]['im_provider']);
398 list($relationQuery, $allRelContactArray) = self
::buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode);
400 // make sure the groups stuff is included only if specifically specified
401 // by the fields param (CRM-1969), else we limit the contacts outputted to only
402 // ones that are part of a group
403 if (!empty($returnProperties['groups'])) {
404 $oldClause = "( contact_a.id = civicrm_group_contact.contact_id )";
405 $newClause = " ( $oldClause AND ( civicrm_group_contact.status = 'Added' OR civicrm_group_contact.status IS NULL ) )";
406 // total hack for export, CRM-3618
407 $from = str_replace($oldClause,
413 if (!$selectAll && $componentTable) {
414 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
416 elseif ($componentClause) {
418 $where = "WHERE $componentClause";
421 $where .= " AND $componentClause";
425 // CRM-13982 - check if is deleted
426 $excludeTrashed = TRUE;
427 foreach ($params as $value) {
428 if ($value[0] == 'contact_is_deleted') {
429 $excludeTrashed = FALSE;
432 $trashClause = $excludeTrashed ?
"contact_a.is_deleted != 1" : "( 1 )";
435 $where = "WHERE $trashClause";
438 $where .= " AND $trashClause";
441 $queryString = "$select $from $where $having";
443 $groupBy = self
::getGroupBy($exportMode, $queryMode, $returnProperties, $query);
445 $queryString .= $groupBy;
448 // always add contact_a.id to the ORDER clause
449 // so the order is deterministic
451 if (strpos('contact_a.id', $order) === FALSE) {
452 $order .= ", contact_a.id";
455 list($field, $dir) = explode(' ', $order, 2);
456 $field = trim($field);
457 if (!empty($returnProperties[$field])) {
459 $queryString .= " ORDER BY $order";
463 $addPaymentHeader = FALSE;
465 $paymentDetails = array();
466 if ($processor->isExportPaymentFields() ||
$selectedPaymentFields) {
468 // get payment related in for event and members
469 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
470 //get all payment headers.
471 // If we haven't selected specific payment fields, load in all the
473 if (!$selectedPaymentFields) {
474 $paymentHeaders = self
::componentPaymentFields();
475 if (!empty($paymentDetails)) {
476 $addPaymentHeader = TRUE;
479 // If we have selected specific payment fields, leave the payment headers
480 // as an empty array; the headers for each selected field will be added
483 $paymentHeaders = array();
485 $nullContributionDetails = array_fill_keys(array_keys($paymentHeaders), NULL);
488 $componentDetails = array();
491 $rowCount = self
::EXPORT_ROW_COUNT
;
493 // we write to temp table often to avoid using too much memory
498 // for CRM-3157 purposes
499 $i18n = CRM_Core_I18n
::singleton();
501 list($outputColumns, $headerRows, $sqlColumns, $metadata) = self
::getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields);
503 $limitReached = FALSE;
504 while (!$limitReached) {
505 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
506 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
507 // If this is less than our limit by the end of the iteration we do not need to run the query again to
508 // check if some remain.
509 $rowsThisIteration = 0;
511 while ($iterationDAO->fetch()) {
513 $rowsThisIteration++
;
515 $query->convertToPseudoNames($iterationDAO);
517 //first loop through output columns so that we return what is required, and in same order.
518 foreach ($outputColumns as $field => $value) {
520 // add im_provider to $dao object
521 if ($field == 'im_provider' && property_exists($iterationDAO, 'provider_id')) {
522 $iterationDAO->im_provider
= $iterationDAO->provider_id
;
525 //build row values (data)
527 if (property_exists($iterationDAO, $field)) {
528 $fieldValue = $iterationDAO->$field;
529 // to get phone type from phone type id
530 if ($field == 'phone_type_id' && isset($phoneTypes[$fieldValue])) {
531 $fieldValue = $phoneTypes[$fieldValue];
533 elseif ($field == 'provider_id' ||
$field == 'im_provider') {
534 $fieldValue = CRM_Utils_Array
::value($fieldValue, $imProviders);
536 elseif (strstr($field, 'master_id')) {
537 $masterAddressId = NULL;
538 if (isset($iterationDAO->$field)) {
539 $masterAddressId = $iterationDAO->$field;
541 // get display name of contact that address is shared.
542 $fieldValue = CRM_Contact_BAO_Contact
::getMasterDisplayName($masterAddressId);
546 if ($processor->isRelationshipTypeKey($field)) {
547 $relDAO = CRM_Utils_Array
::value($iterationDAO->contact_id
, $allRelContactArray[$field]);
548 $relationQuery[$field]->convertToPseudoNames($relDAO);
549 self
::fetchRelationshipDetails($relDAO, $value, $field, $row);
552 $row[$field] = self
::getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId);
556 // add payment headers if required
557 if ($addPaymentHeader && $processor->isExportPaymentFields()) {
558 // @todo rather than do this for every single row do it before the loop starts.
559 // where other header definitions take place.
560 $headerRows = array_merge($headerRows, $paymentHeaders);
561 foreach (array_keys($paymentHeaders) as $paymentHdr) {
562 self
::sqlColumnDefn($processor, $sqlColumns, $paymentHdr);
567 $exportTempTable = self
::createTempTable($sqlColumns);
570 //build header only once
573 // If specific payment fields have been selected for export, payment
574 // data will already be in $row. Otherwise, add payment related
575 // information, if appropriate.
576 if ($addPaymentHeader) {
577 if (!$selectedPaymentFields) {
578 if ($processor->isExportPaymentFields()) {
579 $paymentData = CRM_Utils_Array
::value($row[$paymentTableId], $paymentDetails);
580 if (!is_array($paymentData) ||
empty($paymentData)) {
581 $paymentData = $nullContributionDetails;
583 $row = array_merge($row, $paymentData);
585 elseif (!empty($paymentDetails)) {
586 $row = array_merge($row, $nullContributionDetails);
590 //remove organization name for individuals if it is set for current employer
591 if (!empty($row['contact_type']) &&
592 $row['contact_type'] == 'Individual' && array_key_exists('organization_name', $row)
594 $row['organization_name'] = '';
597 // add component info
598 // write the row to a file
599 $componentDetails[] = $row;
601 // output every $tempRowCount rows
602 if ($count %
$tempRowCount == 0) {
603 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
604 $componentDetails = array();
607 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
608 $limitReached = TRUE;
610 $offset +
= $rowCount;
613 if ($exportTempTable) {
614 self
::writeDetailsToTable($exportTempTable, $componentDetails, $sqlColumns);
616 // if postalMailing option is checked, exclude contacts who are deceased, have
617 // "Do not mail" privacy setting, or have no street address
618 if (isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
619 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
621 self
::postalMailingFormat($exportTempTable, $headerRows, $sqlColumns, $exportMode);
624 // do merge same address and merge same household processing
625 if ($mergeSameAddress) {
626 self
::mergeSameAddress($exportTempTable, $headerRows, $sqlColumns, $exportParams);
629 // merge the records if they have corresponding households
630 if ($mergeSameHousehold) {
631 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$memberOfHouseholdRelationshipKey);
632 self
::mergeSameHousehold($exportTempTable, $headerRows, $sqlColumns, self
::$headOfHouseholdRelationshipKey);
636 CRM_Utils_Hook
::export($exportTempTable, $headerRows, $sqlColumns, $exportMode);
638 // In order to be able to write a unit test against this function we need to suppress
639 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
640 if (empty($exportParams['suppress_csv_for_testing'])) {
641 self
::writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode);
644 // return tableName and sqlColumns in test context
645 return array($exportTempTable, $sqlColumns);
648 // delete the export temp table and component table
649 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
650 CRM_Core_DAO
::executeQuery($sql);
651 CRM_Core_DAO
::reenableFullGroupByMode();
652 CRM_Utils_System
::civiExit();
655 CRM_Core_DAO
::reenableFullGroupByMode();
656 throw new CRM_Core_Exception(ts('No records to export'));
661 * Name of the export file based on mode.
663 * @param string $output
671 public static function getExportFileName($output = 'csv', $mode = CRM_Export_Form_Select
::CONTACT_EXPORT
) {
673 case CRM_Export_Form_Select
::CONTACT_EXPORT
:
674 return ts('CiviCRM Contact Search');
676 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
677 return ts('CiviCRM Contribution Search');
679 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
680 return ts('CiviCRM Member Search');
682 case CRM_Export_Form_Select
::EVENT_EXPORT
:
683 return ts('CiviCRM Participant Search');
685 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
686 return ts('CiviCRM Pledge Search');
688 case CRM_Export_Form_Select
::CASE_EXPORT
:
689 return ts('CiviCRM Case Search');
691 case CRM_Export_Form_Select
::GRANT_EXPORT
:
692 return ts('CiviCRM Grant Search');
694 case CRM_Export_Form_Select
::ACTIVITY_EXPORT
:
695 return ts('CiviCRM Activity Search');
700 * Handle import error file creation.
702 public static function invoke() {
703 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
704 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
705 if (empty($parserName) ||
empty($type)) {
709 // clean and ensure parserName is a valid string
710 $parserName = CRM_Utils_String
::munge($parserName);
711 $parserClass = explode('_', $parserName);
713 // make sure parserClass is in the CRM namespace and
714 // at least 3 levels deep
715 if ($parserClass[0] == 'CRM' &&
716 count($parserClass) >= 3
718 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
719 // ensure the functions exists
720 if (method_exists($parserName, 'errorFileName') &&
721 method_exists($parserName, 'saveFileName')
723 $errorFileName = $parserName::errorFileName($type);
724 $saveFileName = $parserName::saveFileName($type);
725 if (!empty($errorFileName) && !empty($saveFileName)) {
726 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
727 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
728 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
729 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
730 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
732 readfile($errorFileName);
736 CRM_Utils_System
::civiExit();
740 * @param $customSearchClass
744 public static function exportCustom($customSearchClass, $formValues, $order) {
745 $ext = CRM_Extension_System
::singleton()->getMapper();
746 if (!$ext->isExtensionClass($customSearchClass)) {
747 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
750 require_once $ext->classToPath($customSearchClass);
752 $search = new $customSearchClass($formValues);
754 $includeContactIDs = FALSE;
755 if ($formValues['radio_ts'] == 'ts_sel') {
756 $includeContactIDs = TRUE;
759 $sql = $search->all(0, 0, $order, $includeContactIDs);
761 $columns = $search->columns();
763 $header = array_keys($columns);
764 $fields = array_values($columns);
767 $dao = CRM_Core_DAO
::executeQuery($sql);
769 if (method_exists($search, 'alterRow')) {
772 while ($dao->fetch()) {
775 foreach ($fields as $field) {
776 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
777 $row[$field] = $dao->$unqualified_field;
780 $search->alterRow($row);
785 CRM_Core_Report_Excel
::writeCSVFile(self
::getExportFileName(), $header, $rows);
786 CRM_Utils_System
::civiExit();
790 * @param \CRM_Export_BAO_ExportProcessor $processor
794 public static function sqlColumnDefn($processor, &$sqlColumns, $field) {
795 if (substr($field, -4) == '_a_b' ||
substr($field, -4) == '_b_a') {
798 $queryFields = $processor->getQueryFields();
800 $fieldName = CRM_Utils_String
::munge(strtolower($field), '_', 64);
801 if ($fieldName == 'id') {
802 $fieldName = 'civicrm_primary_id';
805 // early exit for master_id, CRM-12100
806 // in the DB it is an ID, but in the export, we retrive the display_name of the master record
807 // also for current_employer, CRM-16939
808 if ($fieldName == 'master_id' ||
$fieldName == 'current_employer') {
809 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
813 if (substr($fieldName, -11) == 'campaign_id') {
815 $sqlColumns[$fieldName] = "$fieldName varchar(128)";
819 $lookUp = array('prefix_id', 'suffix_id');
820 // set the sql columns
821 if (isset($queryFields[$field]['type'])) {
822 switch ($queryFields[$field]['type']) {
823 case CRM_Utils_Type
::T_INT
:
824 case CRM_Utils_Type
::T_BOOLEAN
:
825 if (in_array($field, $lookUp)) {
826 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
829 $sqlColumns[$fieldName] = "$fieldName varchar(16)";
833 case CRM_Utils_Type
::T_STRING
:
834 if (isset($queryFields[$field]['maxlength'])) {
835 $sqlColumns[$fieldName] = "$fieldName varchar({$queryFields[$field]['maxlength']})";
838 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
842 case CRM_Utils_Type
::T_TEXT
:
843 case CRM_Utils_Type
::T_LONGTEXT
:
844 case CRM_Utils_Type
::T_BLOB
:
845 case CRM_Utils_Type
::T_MEDIUMBLOB
:
846 $sqlColumns[$fieldName] = "$fieldName longtext";
849 case CRM_Utils_Type
::T_FLOAT
:
850 case CRM_Utils_Type
::T_ENUM
:
851 case CRM_Utils_Type
::T_DATE
:
852 case CRM_Utils_Type
::T_TIME
:
853 case CRM_Utils_Type
::T_TIMESTAMP
:
854 case CRM_Utils_Type
::T_MONEY
:
855 case CRM_Utils_Type
::T_EMAIL
:
856 case CRM_Utils_Type
::T_URL
:
857 case CRM_Utils_Type
::T_CCNUM
:
859 $sqlColumns[$fieldName] = "$fieldName varchar(32)";
864 if (substr($fieldName, -3, 3) == '_id') {
865 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
867 elseif (substr($fieldName, -5, 5) == '_note') {
868 $sqlColumns[$fieldName] = "$fieldName text";
871 $changeFields = array(
877 if (in_array($fieldName, $changeFields)) {
878 $sqlColumns[$fieldName] = "$fieldName text";
881 // set the sql columns for custom data
882 if (isset($queryFields[$field]['data_type'])) {
884 switch ($queryFields[$field]['data_type']) {
886 // May be option labels, which could be up to 512 characters
887 $length = max(512, CRM_Utils_Array
::value('text_length', $queryFields[$field]));
888 $sqlColumns[$fieldName] = "$fieldName varchar($length)";
892 case 'StateProvince':
894 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
898 $sqlColumns[$fieldName] = "$fieldName text";
902 $sqlColumns[$fieldName] = "$fieldName varchar(255)";
907 $sqlColumns[$fieldName] = "$fieldName text";
915 * @param string $tableName
919 public static function writeDetailsToTable($tableName, &$details, &$sqlColumns) {
920 if (empty($details)) {
929 $id = CRM_Core_DAO
::singleValueQuery($sql);
934 $sqlClause = array();
936 foreach ($details as $dontCare => $row) {
938 $valueString = array($id);
939 foreach ($row as $dontCare => $value) {
941 $valueString[] = "''";
944 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
947 $sqlClause[] = '(' . implode(',', $valueString) . ')';
950 $sqlColumnString = '(id, ' . implode(',', array_keys($sqlColumns)) . ')';
952 $sqlValueString = implode(",\n", $sqlClause);
955 INSERT INTO $tableName $sqlColumnString
956 VALUES $sqlValueString
958 CRM_Core_DAO
::executeQuery($sql);
966 public static function createTempTable(&$sqlColumns) {
967 //creating a temporary table for the search result that need be exported
968 $exportTempTable = CRM_Utils_SQL_TempTable
::build()->setDurable()->setCategory('export')->getName();
970 // also create the sql table
971 $sql = "DROP TABLE IF EXISTS {$exportTempTable}";
972 CRM_Core_DAO
::executeQuery($sql);
975 CREATE TABLE {$exportTempTable} (
976 id int unsigned NOT NULL AUTO_INCREMENT,
978 $sql .= implode(",\n", array_values($sqlColumns));
983 // add indexes for street_address and household_name if present
987 'civicrm_primary_id',
990 foreach ($addIndices as $index) {
991 if (isset($sqlColumns[$index])) {
993 INDEX index_{$index}( $index )
999 ) ENGINE=InnoDB DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci
1002 CRM_Core_DAO
::executeQuery($sql);
1003 return $exportTempTable;
1007 * @param string $tableName
1008 * @param $headerRows
1009 * @param $sqlColumns
1010 * @param array $exportParams
1012 public static function mergeSameAddress($tableName, &$headerRows, &$sqlColumns, $exportParams) {
1013 // check if any records are present based on if they have used shared address feature,
1014 // and not based on if city / state .. matches.
1016 SELECT r1.id as copy_id,
1017 r1.civicrm_primary_id as copy_contact_id,
1018 r1.addressee as copy_addressee,
1019 r1.addressee_id as copy_addressee_id,
1020 r1.postal_greeting as copy_postal_greeting,
1021 r1.postal_greeting_id as copy_postal_greeting_id,
1023 r2.civicrm_primary_id as master_contact_id,
1024 r2.postal_greeting as master_postal_greeting,
1025 r2.postal_greeting_id as master_postal_greeting_id,
1026 r2.addressee as master_addressee,
1027 r2.addressee_id as master_addressee_id
1029 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
1030 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
1032 $linkedMerge = self
::_buildMasterCopyArray($sql, $exportParams, TRUE);
1034 // find all the records that have the same street address BUT not in a household
1035 // require match on city and state as well
1037 SELECT r1.id as master_id,
1038 r1.civicrm_primary_id as master_contact_id,
1039 r1.postal_greeting as master_postal_greeting,
1040 r1.postal_greeting_id as master_postal_greeting_id,
1041 r1.addressee as master_addressee,
1042 r1.addressee_id as master_addressee_id,
1044 r2.civicrm_primary_id as copy_contact_id,
1045 r2.postal_greeting as copy_postal_greeting,
1046 r2.postal_greeting_id as copy_postal_greeting_id,
1047 r2.addressee as copy_addressee,
1048 r2.addressee_id as copy_addressee_id
1050 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
1051 r1.city = r2.city AND
1052 r1.state_province_id = r2.state_province_id )
1053 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
1054 AND ( r2.household_name IS NULL OR r2.household_name = '' )
1055 AND ( r1.street_address != '' )
1059 $merge = self
::_buildMasterCopyArray($sql, $exportParams);
1061 // unset ids from $merge already present in $linkedMerge
1062 foreach ($linkedMerge as $masterID => $values) {
1063 $keys = array($masterID);
1064 $keys = array_merge($keys, array_keys($values['copy']));
1065 foreach ($merge as $mid => $vals) {
1066 if (in_array($mid, $keys)) {
1067 unset($merge[$mid]);
1070 foreach ($values['copy'] as $copyId) {
1071 if (in_array($copyId, $keys)) {
1072 unset($merge[$mid]['copy'][$copyId]);
1078 $merge = $merge +
$linkedMerge;
1080 foreach ($merge as $masterID => $values) {
1083 SET addressee = %1, postal_greeting = %2, email_greeting = %3
1087 1 => array($values['addressee'], 'String'),
1088 2 => array($values['postalGreeting'], 'String'),
1089 3 => array($values['emailGreeting'], 'String'),
1090 4 => array($masterID, 'Integer'),
1092 CRM_Core_DAO
::executeQuery($sql, $params);
1094 // delete all copies
1095 $deleteIDs = array_keys($values['copy']);
1096 $deleteIDString = implode(',', $deleteIDs);
1098 DELETE FROM $tableName
1099 WHERE id IN ( $deleteIDString )
1101 CRM_Core_DAO
::executeQuery($sql);
1104 // unset temporary columns that were added for postal mailing format
1105 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
1106 $unsetKeys = array_keys($sqlColumns);
1107 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1108 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
1109 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1116 * @param int $contactId
1117 * @param array $exportParams
1121 public static function _replaceMergeTokens($contactId, $exportParams) {
1122 $greetings = array();
1125 $greetingFields = array(
1129 foreach ($greetingFields as $greeting) {
1130 if (!empty($exportParams[$greeting])) {
1131 $greetingLabel = $exportParams[$greeting];
1132 if (empty($contact)) {
1137 $contact = civicrm_api('contact', 'get', $values);
1139 if (!empty($contact['is_error'])) {
1142 $contact = $contact['values'][$contact['id']];
1145 $tokens = array('contact' => $greetingLabel);
1146 $greetings[$greeting] = CRM_Utils_Token
::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
1153 * The function unsets static part of the string, if token is the dynamic part.
1155 * Example: 'Hello {contact.first_name}' => converted to => '{contact.first_name}'
1156 * i.e 'Hello Alan' => converted to => 'Alan'
1158 * @param string $parsedString
1159 * @param string $defaultGreeting
1160 * @param bool $addressMergeGreetings
1161 * @param string $greetingType
1165 public static function _trimNonTokens(
1166 &$parsedString, $defaultGreeting,
1167 $addressMergeGreetings, $greetingType = 'postal_greeting'
1169 if (!empty($addressMergeGreetings[$greetingType])) {
1170 $greetingLabel = $addressMergeGreetings[$greetingType];
1172 $greetingLabel = empty($greetingLabel) ?
$defaultGreeting : $greetingLabel;
1174 $stringsToBeReplaced = preg_replace('/(\{[a-zA-Z._ ]+\})/', ';;', $greetingLabel);
1175 $stringsToBeReplaced = explode(';;', $stringsToBeReplaced);
1176 foreach ($stringsToBeReplaced as $key => $string) {
1177 // to keep one space
1178 $stringsToBeReplaced[$key] = ltrim($string);
1180 $parsedString = str_replace($stringsToBeReplaced, "", $parsedString);
1182 return $parsedString;
1187 * @param array $exportParams
1188 * @param bool $sharedAddress
1192 public static function _buildMasterCopyArray($sql, $exportParams, $sharedAddress = FALSE) {
1193 static $contactGreetingTokens = array();
1195 $addresseeOptions = CRM_Core_OptionGroup
::values('addressee');
1196 $postalOptions = CRM_Core_OptionGroup
::values('postal_greeting');
1198 $merge = $parents = array();
1199 $dao = CRM_Core_DAO
::executeQuery($sql);
1201 while ($dao->fetch()) {
1202 $masterID = $dao->master_id
;
1203 $copyID = $dao->copy_id
;
1204 $masterPostalGreeting = $dao->master_postal_greeting
;
1205 $masterAddressee = $dao->master_addressee
;
1206 $copyAddressee = $dao->copy_addressee
;
1208 if (!$sharedAddress) {
1209 if (!isset($contactGreetingTokens[$dao->master_contact_id
])) {
1210 $contactGreetingTokens[$dao->master_contact_id
] = self
::_replaceMergeTokens($dao->master_contact_id
, $exportParams);
1212 $masterPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1213 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_postal_greeting
1215 $masterAddressee = CRM_Utils_Array
::value('addressee',
1216 $contactGreetingTokens[$dao->master_contact_id
], $dao->master_addressee
1219 if (!isset($contactGreetingTokens[$dao->copy_contact_id
])) {
1220 $contactGreetingTokens[$dao->copy_contact_id
] = self
::_replaceMergeTokens($dao->copy_contact_id
, $exportParams);
1222 $copyPostalGreeting = CRM_Utils_Array
::value('postal_greeting',
1223 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_postal_greeting
1225 $copyAddressee = CRM_Utils_Array
::value('addressee',
1226 $contactGreetingTokens[$dao->copy_contact_id
], $dao->copy_addressee
1230 if (!isset($merge[$masterID])) {
1231 // check if this is an intermediate child
1232 // this happens if there are 3 or more matches a,b, c
1233 // the above query will return a, b / a, c / b, c
1234 // we might be doing a bit more work, but for now its ok, unless someone
1235 // knows how to fix the query above
1236 if (isset($parents[$masterID])) {
1237 $masterID = $parents[$masterID];
1240 $merge[$masterID] = array(
1241 'addressee' => $masterAddressee,
1243 'postalGreeting' => $masterPostalGreeting,
1245 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
1248 $parents[$copyID] = $masterID;
1250 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
1252 if (!empty($exportParams['postal_greeting_other']) &&
1253 count($merge[$masterID]['copy']) >= 1
1255 // use static greetings specified if no of contacts > 2
1256 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
1258 elseif ($copyPostalGreeting) {
1259 self
::_trimNonTokens($copyPostalGreeting,
1260 $postalOptions[$dao->copy_postal_greeting_id
],
1263 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
1264 // if there happens to be a duplicate, remove it
1265 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
1268 if (!empty($exportParams['addressee_other']) &&
1269 count($merge[$masterID]['copy']) >= 1
1271 // use static greetings specified if no of contacts > 2
1272 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
1274 elseif ($copyAddressee) {
1275 self
::_trimNonTokens($copyAddressee,
1276 $addresseeOptions[$dao->copy_addressee_id
],
1277 $exportParams, 'addressee'
1279 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
1282 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
1289 * Merge household record into the individual record
1292 * @param string $exportTempTable
1293 * Temporary temp table that stores the records.
1294 * @param array $headerRows
1295 * Array of headers for the export file.
1296 * @param array $sqlColumns
1297 * Array of names of the table columns of the temp table.
1298 * @param string $prefix
1299 * Name of the relationship type that is prefixed to the table columns.
1301 public static function mergeSameHousehold($exportTempTable, &$headerRows, &$sqlColumns, $prefix) {
1302 $prefixColumn = $prefix . '_';
1303 $allKeys = array_keys($sqlColumns);
1304 $replaced = array();
1305 $headerRows = array_values($headerRows);
1307 // name map of the non standard fields in header rows & sql columns
1308 $mappingFields = array(
1309 'civicrm_primary_id' => 'id',
1310 'contact_source' => 'source',
1311 'current_employer_id' => 'employer_id',
1312 'contact_is_deleted' => 'is_deleted',
1313 'name' => 'address_name',
1314 'provider_id' => 'im_service_provider',
1315 'phone_type_id' => 'phone_type',
1318 //figure out which columns are to be replaced by which ones
1319 foreach ($sqlColumns as $columnNames => $dontCare) {
1320 if ($rep = CRM_Utils_Array
::value($columnNames, $mappingFields)) {
1321 $replaced[$columnNames] = CRM_Utils_String
::munge($prefixColumn . $rep, '_', 64);
1324 $householdColName = CRM_Utils_String
::munge($prefixColumn . $columnNames, '_', 64);
1326 if (!empty($sqlColumns[$householdColName])) {
1327 $replaced[$columnNames] = $householdColName;
1331 $query = "UPDATE $exportTempTable SET ";
1334 foreach ($replaced as $from => $to) {
1335 $clause[] = "$from = $to ";
1336 unset($sqlColumns[$to]);
1337 if ($key = CRM_Utils_Array
::key($to, $allKeys)) {
1338 unset($headerRows[$key]);
1341 $query .= implode(",\n", $clause);
1342 $query .= " WHERE {$replaced['civicrm_primary_id']} != ''";
1344 CRM_Core_DAO
::executeQuery($query);
1346 //drop the table columns that store redundant household info
1347 $dropQuery = "ALTER TABLE $exportTempTable ";
1348 foreach ($replaced as $householdColumns) {
1349 $dropClause[] = " DROP $householdColumns ";
1351 $dropQuery .= implode(",\n", $dropClause);
1353 CRM_Core_DAO
::executeQuery($dropQuery);
1355 // also drop the temp table if exists
1356 $sql = "DROP TABLE IF EXISTS {$exportTempTable}_temp";
1357 CRM_Core_DAO
::executeQuery($sql);
1359 // clean up duplicate records
1361 CREATE TABLE {$exportTempTable}_temp SELECT *
1362 FROM {$exportTempTable}
1363 GROUP BY civicrm_primary_id ";
1365 CRM_Core_DAO
::executeQuery($query);
1367 $query = "DROP TABLE $exportTempTable";
1368 CRM_Core_DAO
::executeQuery($query);
1370 $query = "ALTER TABLE {$exportTempTable}_temp RENAME TO {$exportTempTable}";
1371 CRM_Core_DAO
::executeQuery($query);
1375 * @param $exportTempTable
1376 * @param $headerRows
1377 * @param $sqlColumns
1378 * @param $exportMode
1379 * @param null $saveFile
1380 * @param string $batchItems
1382 public static function writeCSVFromTable($exportTempTable, $headerRows, $sqlColumns, $exportMode, $saveFile = NULL, $batchItems = '') {
1383 $writeHeader = TRUE;
1385 $limit = self
::EXPORT_ROW_COUNT
;
1387 $query = "SELECT * FROM $exportTempTable";
1390 $limitQuery = $query . "
1391 LIMIT $offset, $limit
1393 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
1399 $componentDetails = array();
1400 while ($dao->fetch()) {
1403 foreach ($sqlColumns as $column => $dontCare) {
1404 $row[$column] = $dao->$column;
1406 $componentDetails[] = $row;
1408 if ($exportMode == 'financial') {
1409 $getExportFileName = 'CiviCRM Contribution Search';
1412 $getExportFileName = self
::getExportFileName('csv', $exportMode);
1414 $csvRows = CRM_Core_Report_Excel
::writeCSVFile($getExportFileName,
1421 if ($saveFile && !empty($csvRows)) {
1422 $batchItems .= $csvRows;
1425 $writeHeader = FALSE;
1431 * Manipulate header rows for relationship fields.
1433 * @param $headerRows
1435 public static function manipulateHeaderRows(&$headerRows) {
1436 foreach ($headerRows as & $header) {
1437 $split = explode('-', $header);
1438 if ($relationTypeName = CRM_Utils_Array
::value($split[0], self
::$relationshipTypes)) {
1439 $split[0] = $relationTypeName;
1440 $header = implode('-', $split);
1446 * Exclude contacts who are deceased, have "Do not mail" privacy setting,
1447 * or have no street address
1448 * @param $exportTempTable
1449 * @param $headerRows
1450 * @param $sqlColumns
1451 * @param $exportParams
1453 public static function postalMailingFormat($exportTempTable, &$headerRows, &$sqlColumns, $exportParams) {
1454 $whereClause = array();
1456 if (array_key_exists('is_deceased', $sqlColumns)) {
1457 $whereClause[] = 'is_deceased = 1';
1460 if (array_key_exists('do_not_mail', $sqlColumns)) {
1461 $whereClause[] = 'do_not_mail = 1';
1464 if (array_key_exists('street_address', $sqlColumns)) {
1465 $addressWhereClause = " ( (street_address IS NULL) OR (street_address = '') ) ";
1467 // check for supplemental_address_1
1468 if (array_key_exists('supplemental_address_1', $sqlColumns)) {
1469 $addressOptions = CRM_Core_BAO_Setting
::valueOptions(CRM_Core_BAO_Setting
::SYSTEM_PREFERENCES_NAME
,
1470 'address_options', TRUE, NULL, TRUE
1472 if (!empty($addressOptions['supplemental_address_1'])) {
1473 $addressWhereClause .= " AND ( (supplemental_address_1 IS NULL) OR (supplemental_address_1 = '') ) ";
1474 // enclose it again, since we are doing an AND in between a set of ORs
1475 $addressWhereClause = "( $addressWhereClause )";
1479 $whereClause[] = $addressWhereClause;
1482 if (!empty($whereClause)) {
1483 $whereClause = implode(' OR ', $whereClause);
1486 FROM $exportTempTable
1487 WHERE {$whereClause}";
1488 CRM_Core_DAO
::singleValueQuery($query);
1491 // unset temporary columns that were added for postal mailing format
1492 if (!empty($exportParams['postal_mailing_export']['temp_columns'])) {
1493 $unsetKeys = array_keys($sqlColumns);
1494 foreach ($unsetKeys as $headerKey => $sqlColKey) {
1495 if (array_key_exists($sqlColKey, $exportParams['postal_mailing_export']['temp_columns'])) {
1496 unset($sqlColumns[$sqlColKey], $headerRows[$headerKey]);
1503 * Build componentPayment fields.
1505 public static function componentPaymentFields() {
1506 static $componentPaymentFields;
1507 if (!isset($componentPaymentFields)) {
1508 $componentPaymentFields = array(
1509 'componentPaymentField_total_amount' => ts('Total Amount'),
1510 'componentPaymentField_contribution_status' => ts('Contribution Status'),
1511 'componentPaymentField_received_date' => ts('Date Received'),
1512 'componentPaymentField_payment_instrument' => ts('Payment Method'),
1513 'componentPaymentField_transaction_id' => ts('Transaction ID'),
1516 return $componentPaymentFields;
1520 * Set the definition for the header rows and sql columns based on the field to output.
1522 * @param string $field
1523 * @param array $headerRows
1524 * @param array $sqlColumns
1525 * Columns to go in the temp table.
1526 * @param \CRM_Export_BAO_ExportProcessor $processor
1527 * @param array|string $value
1528 * @param array $phoneTypes
1529 * @param array $imProviders
1530 * @param string $relationQuery
1531 * @param array $selectedPaymentFields
1534 public static function setHeaderRows($field, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields) {
1536 $queryFields = $processor->getQueryFields();
1537 // Split campaign into 2 fields for id and title
1538 if (substr($field, -14) == 'campaign_title') {
1539 $headerRows[] = ts('Campaign Title');
1541 elseif (substr($field, -11) == 'campaign_id') {
1542 $headerRows[] = ts('Campaign ID');
1544 elseif (isset($queryFields[$field]['title'])) {
1545 $headerRows[] = $queryFields[$field]['title'];
1547 elseif ($field == 'phone_type_id') {
1548 $headerRows[] = ts('Phone Type');
1550 elseif ($field == 'provider_id') {
1551 $headerRows[] = ts('IM Service Provider');
1553 elseif ($processor->isRelationshipTypeKey($field)) {
1554 foreach ($value as $relationField => $relationValue) {
1555 // below block is same as primary block (duplicate)
1556 if (isset($relationQuery[$field]->_fields
[$relationField]['title'])) {
1557 if ($relationQuery[$field]->_fields
[$relationField]['name'] == 'name') {
1558 $headerName = $field . '-' . $relationField;
1561 if ($relationField == 'current_employer') {
1562 $headerName = $field . '-' . 'current_employer';
1565 $headerName = $field . '-' . $relationQuery[$field]->_fields
[$relationField]['name'];
1569 $headerRows[] = $headerName;
1571 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1573 elseif ($relationField == 'phone_type_id') {
1574 $headerName = $field . '-' . 'Phone Type';
1575 $headerRows[] = $headerName;
1576 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1578 elseif ($relationField == 'provider_id') {
1579 $headerName = $field . '-' . 'Im Service Provider';
1580 $headerRows[] = $headerName;
1581 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1583 elseif ($relationField == 'state_province_id') {
1584 $headerName = $field . '-' . 'state_province_id';
1585 $headerRows[] = $headerName;
1586 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1588 elseif (is_array($relationValue) && $relationField == 'location') {
1589 // fix header for location type case
1590 foreach ($relationValue as $ltype => $val) {
1591 foreach (array_keys($val) as $fld) {
1592 $type = explode('-', $fld);
1594 $hdr = "{$ltype}-" . $relationQuery[$field]->_fields
[$type[0]]['title'];
1596 if (!empty($type[1])) {
1597 if (CRM_Utils_Array
::value(0, $type) == 'phone') {
1598 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1600 elseif (CRM_Utils_Array
::value(0, $type) == 'im') {
1601 $hdr .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1604 $headerName = $field . '-' . $hdr;
1605 $headerRows[] = $headerName;
1606 self
::sqlColumnDefn($processor, $sqlColumns, $headerName);
1611 self
::manipulateHeaderRows($headerRows);
1613 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
1614 $headerRows[] = CRM_Utils_Array
::value($field, self
::componentPaymentFields());
1617 $headerRows[] = $field;
1620 self
::sqlColumnDefn($processor, $sqlColumns, $field);
1622 return array($headerRows, $sqlColumns);
1626 * Get the various arrays that we use to structure our output.
1628 * The extraction of these has been moved to a separate function for clarity and so that
1629 * tests can be added - in particular on the $outputHeaders array.
1631 * However it still feels a bit like something that I'm too polite to write down and this should be seen
1632 * as a step on the refactoring path rather than how it should be.
1634 * @param array $returnProperties
1635 * @param \CRM_Export_BAO_ExportProcessor $processor
1636 * @param string $relationQuery
1637 * @param array $selectedPaymentFields
1639 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
1640 * alias for the field generated by BAO_Query object.
1641 * - headerRows Array of the column header strings to put in the csv header - non-associative.
1642 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
1643 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
1644 * I'm too embarassed to discuss here.
1646 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
1647 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
1648 * in the main DAO loop is done once per row & that coule be 100,000 times.)
1649 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
1650 * - a) the function used is more efficient or
1651 * - b) this code is old & outdated. Submit your answers to circular bin or better
1652 * yet find a way to comment them for posterity.
1654 public static function getExportStructureArrays($returnProperties, $processor, $relationQuery, $selectedPaymentFields) {
1655 $metadata = $headerRows = $outputColumns = $sqlColumns = array();
1656 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1657 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1659 $queryFields = $processor->getQueryFields();
1660 foreach ($returnProperties as $key => $value) {
1661 if ($key != 'location' ||
!is_array($value)) {
1662 $outputColumns[$key] = $value;
1663 list($headerRows, $sqlColumns) = self
::setHeaderRows($key, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1666 foreach ($value as $locationType => $locationFields) {
1667 foreach (array_keys($locationFields) as $locationFieldName) {
1668 $type = explode('-', $locationFieldName);
1670 $actualDBFieldName = $type[0];
1671 $outputFieldName = $locationType . '-' . $queryFields[$actualDBFieldName]['title'];
1672 $daoFieldName = CRM_Utils_String
::munge($locationType) . '-' . $actualDBFieldName;
1674 if (!empty($type[1])) {
1675 $daoFieldName .= "-" . $type[1];
1676 if ($actualDBFieldName == 'phone') {
1677 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $phoneTypes);
1679 elseif ($actualDBFieldName == 'im') {
1680 $outputFieldName .= "-" . CRM_Utils_Array
::value($type[1], $imProviders);
1683 if ($type[0] == 'im_provider') {
1684 // Warning: shame inducing hack.
1685 $metadata[$daoFieldName]['pseudoconstant']['var'] = 'imProviders';
1687 self
::sqlColumnDefn($processor, $sqlColumns, $outputFieldName);
1688 list($headerRows, $sqlColumns) = self
::setHeaderRows($outputFieldName, $headerRows, $sqlColumns, $processor, $value, $phoneTypes, $imProviders, $relationQuery, $selectedPaymentFields);
1689 if ($actualDBFieldName == 'country' ||
$actualDBFieldName == 'world_region') {
1690 $metadata[$daoFieldName] = array('context' => 'country');
1692 if ($actualDBFieldName == 'state_province') {
1693 $metadata[$daoFieldName] = array('context' => 'province');
1695 $outputColumns[$daoFieldName] = TRUE;
1700 return array($outputColumns, $headerRows, $sqlColumns, $metadata);
1704 * Get the values of linked household contact.
1706 * @param CRM_Core_DAO $relDAO
1707 * @param array $value
1708 * @param string $field
1711 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
1712 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
1713 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
1714 $i18n = CRM_Core_I18n
::singleton();
1715 foreach ($value as $relationField => $relationValue) {
1716 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
1717 $fieldValue = $relDAO->$relationField;
1718 if ($relationField == 'phone_type_id') {
1719 $fieldValue = $phoneTypes[$relationValue];
1721 elseif ($relationField == 'provider_id') {
1722 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
1725 elseif (is_object($relDAO) && in_array($relationField, array(
1731 //special case for greeting replacement
1732 $fldValue = "{$relationField}_display";
1733 $fieldValue = $relDAO->$fldValue;
1736 elseif (is_object($relDAO) && $relationField == 'state_province') {
1737 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
1739 elseif (is_object($relDAO) && $relationField == 'country') {
1740 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
1745 $field = $field . '_';
1746 $relPrefix = $field . $relationField;
1748 if (is_object($relDAO) && $relationField == 'id') {
1749 $row[$relPrefix] = $relDAO->contact_id
;
1751 elseif (is_array($relationValue) && $relationField == 'location') {
1752 foreach ($relationValue as $ltype => $val) {
1753 foreach (array_keys($val) as $fld) {
1754 $type = explode('-', $fld);
1755 $fldValue = "{$ltype}-" . $type[0];
1756 if (!empty($type[1])) {
1757 $fldValue .= "-" . $type[1];
1759 // CRM-3157: localise country, region (both have ‘country’ context)
1760 // and state_province (‘province’ context)
1762 case (!is_object($relDAO)):
1763 $row[$field . '_' . $fldValue] = '';
1766 case in_array('country', $type):
1767 case in_array('world_region', $type):
1768 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1769 array('context' => 'country')
1773 case in_array('state_province', $type):
1774 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1775 array('context' => 'province')
1780 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1786 elseif (isset($fieldValue) && $fieldValue != '') {
1787 //check for custom data
1788 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
1789 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1792 //normal relationship fields
1793 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1794 switch ($relationField) {
1796 case 'world_region':
1797 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'country'));
1800 case 'state_province':
1801 $row[$relPrefix] = $i18n->crm_translate($fieldValue, array('context' => 'province'));
1805 $row[$relPrefix] = $fieldValue;
1811 // if relation field is empty or null
1812 $row[$relPrefix] = '';
1818 * Get the ids that we want to get related contact details for.
1821 * @param int $exportMode
1825 protected static function getIDsForRelatedContact($ids, $exportMode) {
1826 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
1829 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
1831 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1832 $dao = CRM_Core_DAO
::executeQuery("
1833 SELECT contact_id FROM civicrm_activity_contact
1834 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1835 record_type_id = {$sourceID}
1838 while ($dao->fetch()) {
1839 $relIDs[] = $dao->contact_id
;
1843 $component = self
::exportComponent($exportMode);
1845 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
1846 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
1849 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
1856 * @param $exportMode
1857 * @param $componentTable
1858 * @param $returnProperties
1862 protected static function buildRelatedContactArray($selectAll, $ids, $exportMode, $componentTable, $returnProperties, $queryMode) {
1863 $allRelContactArray = $relationQuery = array();
1865 foreach (self
::$relationshipTypes as $rel => $dnt) {
1866 if ($relationReturnProperties = CRM_Utils_Array
::value($rel, $returnProperties)) {
1867 $allRelContactArray[$rel] = array();
1868 // build Query for each relationship
1869 $relationQuery[$rel] = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1870 NULL, FALSE, FALSE, $queryMode
1872 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery[$rel]->query();
1874 list($id, $direction) = explode('_', $rel, 2);
1875 // identify the relationship direction
1876 $contactA = 'contact_id_a';
1877 $contactB = 'contact_id_b';
1878 if ($direction == 'b_a') {
1879 $contactA = 'contact_id_b';
1880 $contactB = 'contact_id_a';
1882 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
1884 $relationshipJoin = $relationshipClause = '';
1885 if (!$selectAll && $componentTable) {
1886 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1888 elseif (!empty($relIDs)) {
1889 $relID = implode(',', $relIDs);
1890 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1893 $relationFrom = " {$relationFrom}
1894 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1895 {$relationshipJoin} ";
1897 //check for active relationship status only
1898 $today = date('Ymd');
1899 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1900 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1901 $relationGroupBy = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($relationQuery[$rel]->_select
, "crel.{$contactA}");
1902 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1903 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving $relationGroupBy";
1905 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
1906 while ($allRelContactDAO->fetch()) {
1907 //FIX Me: Migrate this to table rather than array
1908 // build the array of all related contacts
1909 $allRelContactArray[$rel][$allRelContactDAO->refContact
] = clone($allRelContactDAO);
1911 $allRelContactDAO->free();
1914 return array($relationQuery, $allRelContactArray);
1919 * @param $iterationDAO
1920 * @param $fieldValue
1923 * @param $selectedPaymentFields
1924 * @param $paymentDetails
1925 * @param string $paymentTableId
1928 protected static function getTransformedFieldValue($field, $iterationDAO, $fieldValue, $i18n, $metadata, $selectedPaymentFields, $paymentDetails, $paymentTableId) {
1930 if ($field == 'id') {
1931 return $iterationDAO->contact_id
;
1932 // special case for calculated field
1934 elseif ($field == 'source_contact_id') {
1935 return $iterationDAO->contact_id
;
1937 elseif ($field == 'pledge_balance_amount') {
1938 return $iterationDAO->pledge_amount
- $iterationDAO->pledge_total_paid
;
1939 // special case for calculated field
1941 elseif ($field == 'pledge_next_pay_amount') {
1942 return $iterationDAO->pledge_next_pay_amount +
$iterationDAO->pledge_outstanding_amount
;
1944 elseif (isset($fieldValue) &&
1947 //check for custom data
1948 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($field)) {
1949 return CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
1952 elseif (in_array($field, array(
1957 //special case for greeting replacement
1958 $fldValue = "{$field}_display";
1959 return $iterationDAO->$fldValue;
1962 //normal fields with a touch of CRM-3157
1965 case 'world_region':
1966 return $i18n->crm_translate($fieldValue, array('context' => 'country'));
1968 case 'state_province':
1969 return $i18n->crm_translate($fieldValue, array('context' => 'province'));
1972 case 'preferred_communication_method':
1973 case 'preferred_mail_format':
1974 case 'communication_style':
1975 return $i18n->crm_translate($fieldValue);
1978 if (isset($metadata[$field])) {
1979 // No I don't know why we do it this way & whether we could
1980 // make better use of pseudoConstants.
1981 if (!empty($metadata[$field]['context'])) {
1982 return $i18n->crm_translate($fieldValue, $metadata[$field]);
1984 if (!empty($metadata[$field]['pseudoconstant'])) {
1985 // This is not our normal syntax for pseudoconstants but I am a bit loath to
1986 // call an external function until sure it is not increasing php processing given this
1987 // may be iterated 100,000 times & we already have the $imProvider var loaded.
1988 // That can be next refactor...
1989 // Yes - definitely feeling hatred for this bit of code - I know you will beat me up over it's awfulness
1990 // but I have to reach a stable point....
1991 $varName = $metadata[$field]['pseudoconstant']['var'];
1992 if ($varName === 'imProviders') {
1993 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_IM', 'provider_id', $fieldValue);
1995 if ($varName === 'phoneTypes') {
1996 return CRM_Core_PseudoConstant
::getLabel('CRM_Core_DAO_Phone', 'phone_type_id', $fieldValue);
2005 elseif ($selectedPaymentFields && array_key_exists($field, self
::componentPaymentFields())) {
2006 $paymentData = CRM_Utils_Array
::value($iterationDAO->$paymentTableId, $paymentDetails);
2007 $payFieldMapper = array(
2008 'componentPaymentField_total_amount' => 'total_amount',
2009 'componentPaymentField_contribution_status' => 'contribution_status',
2010 'componentPaymentField_payment_instrument' => 'pay_instru',
2011 'componentPaymentField_transaction_id' => 'trxn_id',
2012 'componentPaymentField_received_date' => 'receive_date',
2014 return CRM_Utils_Array
::value($payFieldMapper[$field], $paymentData, '');
2017 // if field is empty or null