3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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-2019
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 * Get Export component
47 * @param int $exportMode
51 * CiviCRM Export Component
53 public static function exportComponent($exportMode) {
54 switch ($exportMode) {
55 case CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
:
56 $component = 'civicrm_contribution';
59 case CRM_Export_Form_Select
::EVENT_EXPORT
:
60 $component = 'civicrm_participant';
63 case CRM_Export_Form_Select
::MEMBER_EXPORT
:
64 $component = 'civicrm_membership';
67 case CRM_Export_Form_Select
::PLEDGE_EXPORT
:
68 $component = 'civicrm_pledge';
71 case CRM_Export_Form_Select
::GRANT_EXPORT
:
72 $component = 'civicrm_grant';
79 * Get the list the export fields.
81 * @param int $selectAll
82 * User preference while export.
85 * @param array $params
86 * Associated array of fields.
87 * @param string $order
89 * @param array $fields
90 * Associated array of fields.
91 * @param array $moreReturnProperties
92 * Additional return fields.
93 * @param int $exportMode
95 * @param string $componentClause
97 * @param string $componentTable
99 * @param bool $mergeSameAddress
100 * Merge records if they have same address.
101 * @param bool $mergeSameHousehold
102 * Merge records if they belong to the same household.
104 * @param array $exportParams
105 * @param string $queryOperator
108 * An array can be requested from within a unit test.
110 * @throws \CRM_Core_Exception
112 public static function exportComponents(
118 $moreReturnProperties = NULL,
119 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
120 $componentClause = NULL,
121 $componentTable = NULL,
122 $mergeSameAddress = FALSE,
123 $mergeSameHousehold = FALSE,
125 $queryOperator = 'AND'
129 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
130 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
133 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
134 // If an Additional Group is selected, then all contacts in that group are
135 // added to the export set (filtering out duplicates).
136 // Really - the calling function could do this ... just saying
137 // @todo take a whip to the calling function.
138 CRM_Core_DAO
::executeQuery("
139 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"
142 // rectify params to what proximity search expects if there is a value for prox_distance
144 // @todo - move this back to the calling functions
145 if (!empty($params)) {
146 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
148 // @todo everything from this line up should go back to the calling functions.
149 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress, $exportParams);
150 if ($moreReturnProperties) {
151 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
153 $processor->setComponentTable($componentTable);
154 $processor->setComponentClause($componentClause);
156 list($query, $queryString) = $processor->runQuery($params, $order);
158 // This perhaps only needs calling when $mergeSameHousehold == 1
159 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
161 $addPaymentHeader = FALSE;
163 list($outputColumns, $metadata) = $processor->getExportStructureArrays();
165 if ($processor->isMergeSameAddress()) {
166 foreach (array_keys($processor->getAdditionalFieldsForSameAddressMerge()) as $field) {
167 $processor->setColumnAsCalculationOnly($field);
171 $paymentDetails = [];
172 if ($processor->isExportPaymentFields()) {
173 // get payment related in for event and members
174 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
175 //get all payment headers.
176 // If we haven't selected specific payment fields, load in all the
178 if (!$processor->isExportSpecifiedPaymentFields()) {
179 if (!empty($paymentDetails)) {
180 $addPaymentHeader = TRUE;
181 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
182 $processor->addOutputSpecification($paymentField);
188 $componentDetails = [];
190 $rowCount = self
::EXPORT_ROW_COUNT
;
192 // we write to temp table often to avoid using too much memory
197 $headerRows = $processor->getHeaderRows();
198 $sqlColumns = $processor->getSQLColumns();
199 $processor->createTempTable();
200 $limitReached = FALSE;
202 while (!$limitReached) {
203 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
204 CRM_Core_DAO
::disableFullGroupByMode();
205 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
206 CRM_Core_DAO
::reenableFullGroupByMode();
207 // If this is less than our limit by the end of the iteration we do not need to run the query again to
208 // check if some remain.
209 $rowsThisIteration = 0;
211 while ($iterationDAO->fetch()) {
213 $rowsThisIteration++
;
214 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader);
215 if ($row === FALSE) {
219 // add component info
220 // write the row to a file
221 $componentDetails[] = $row;
223 // output every $tempRowCount rows
224 if ($count %
$tempRowCount == 0) {
225 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
226 $componentDetails = [];
229 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
230 $limitReached = TRUE;
232 $offset +
= $rowCount;
235 if ($processor->getTemporaryTable()) {
236 self
::writeDetailsToTable($processor, $componentDetails);
238 // do merge same address and merge same household processing
239 if ($mergeSameAddress) {
240 $processor->mergeSameAddress();
244 $table = $processor->getTemporaryTable();
245 CRM_Utils_Hook
::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
246 if ($table !== $processor->getTemporaryTable()) {
247 CRM_Core_Error
::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
248 $processor->setTemporaryTable($table);
251 // In order to be able to write a unit test against this function we need to suppress
252 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
253 if (empty($exportParams['suppress_csv_for_testing'])) {
254 self
::writeCSVFromTable($headerRows, $sqlColumns, $processor);
257 // return tableName sqlColumns headerRows in test context
258 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
261 // delete the export temp table and component table
262 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
263 CRM_Core_DAO
::executeQuery($sql);
264 CRM_Core_DAO
::reenableFullGroupByMode();
265 CRM_Utils_System
::civiExit(0, ['processor' => $processor]);
268 CRM_Core_DAO
::reenableFullGroupByMode();
269 throw new CRM_Core_Exception(ts('No records to export'));
274 * Handle import error file creation.
276 public static function invoke() {
277 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
278 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
279 if (empty($parserName) ||
empty($type)) {
283 // clean and ensure parserName is a valid string
284 $parserName = CRM_Utils_String
::munge($parserName);
285 $parserClass = explode('_', $parserName);
287 // make sure parserClass is in the CRM namespace and
288 // at least 3 levels deep
289 if ($parserClass[0] == 'CRM' &&
290 count($parserClass) >= 3
292 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
293 // ensure the functions exists
294 if (method_exists($parserName, 'errorFileName') &&
295 method_exists($parserName, 'saveFileName')
297 $errorFileName = $parserName::errorFileName($type);
298 $saveFileName = $parserName::saveFileName($type);
299 if (!empty($errorFileName) && !empty($saveFileName)) {
300 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
301 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
302 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
303 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
304 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
306 readfile($errorFileName);
310 CRM_Utils_System
::civiExit();
314 * @param $customSearchClass
318 public static function exportCustom($customSearchClass, $formValues, $order) {
319 $ext = CRM_Extension_System
::singleton()->getMapper();
320 if (!$ext->isExtensionClass($customSearchClass)) {
321 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
324 require_once $ext->classToPath($customSearchClass);
326 $search = new $customSearchClass($formValues);
328 $includeContactIDs = FALSE;
329 if ($formValues['radio_ts'] == 'ts_sel') {
330 $includeContactIDs = TRUE;
333 $sql = $search->all(0, 0, $order, $includeContactIDs);
335 $columns = $search->columns();
337 $header = array_keys($columns);
338 $fields = array_values($columns);
341 $dao = CRM_Core_DAO
::executeQuery($sql);
343 if (method_exists($search, 'alterRow')) {
346 while ($dao->fetch()) {
349 foreach ($fields as $field) {
350 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
351 $row[$field] = $dao->$unqualified_field;
354 $search->alterRow($row);
359 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
360 CRM_Utils_System
::civiExit();
364 * @param \CRM_Export_BAO_ExportProcessor $processor
367 public static function writeDetailsToTable($processor, $details) {
368 $tableName = $processor->getTemporaryTable();
369 if (empty($details)) {
378 $id = CRM_Core_DAO
::singleValueQuery($sql);
385 foreach ($details as $row) {
387 $valueString = [$id];
388 foreach ($row as $value) {
390 $valueString[] = "''";
393 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
396 $sqlClause[] = '(' . implode(',', $valueString) . ')';
398 $sqlColumns = array_merge(['id' => 1], $processor->getSQLColumns());
399 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
401 $sqlValueString = implode(",\n", $sqlClause);
404 INSERT INTO $tableName $sqlColumnString
405 VALUES $sqlValueString
407 CRM_Core_DAO
::executeQuery($sql);
413 * @param \CRM_Export_BAO_ExportProcessor $processor
415 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
416 $exportTempTable = $processor->getTemporaryTable();
419 $limit = self
::EXPORT_ROW_COUNT
;
421 $query = "SELECT * FROM $exportTempTable";
424 $limitQuery = $query . "
425 LIMIT $offset, $limit
427 $dao = CRM_Core_DAO
::executeQuery($limitQuery);
433 $componentDetails = [];
434 while ($dao->fetch()) {
437 foreach (array_keys($processor->getSQLColumns()) as $column) {
438 $row[$column] = $dao->$column;
440 $componentDetails[] = $row;
442 CRM_Core_Report_Excel
::writeCSVFile($processor->getExportFileName(),
449 $writeHeader = FALSE;
455 * Get the values of linked household contact.
457 * @param CRM_Core_DAO $relDAO
458 * @param array $value
459 * @param string $field
462 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
463 $phoneTypes = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_Phone', 'phone_type_id');
464 $imProviders = CRM_Core_PseudoConstant
::get('CRM_Core_DAO_IM', 'provider_id');
465 $i18n = CRM_Core_I18n
::singleton();
466 $field = $field . '_';
468 foreach ($value as $relationField => $relationValue) {
469 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
470 $fieldValue = $relDAO->$relationField;
471 if ($relationField == 'phone_type_id') {
472 $fieldValue = $phoneTypes[$relationValue];
474 elseif ($relationField == 'provider_id') {
475 $fieldValue = CRM_Utils_Array
::value($relationValue, $imProviders);
478 elseif (is_object($relDAO) && in_array($relationField, [
483 //special case for greeting replacement
484 $fldValue = "{$relationField}_display";
485 $fieldValue = $relDAO->$fldValue;
488 elseif (is_object($relDAO) && $relationField == 'state_province') {
489 $fieldValue = CRM_Core_PseudoConstant
::stateProvince($relDAO->state_province_id
);
491 elseif (is_object($relDAO) && $relationField == 'country') {
492 $fieldValue = CRM_Core_PseudoConstant
::country($relDAO->country_id
);
497 $relPrefix = $field . $relationField;
499 if (is_object($relDAO) && $relationField == 'id') {
500 $row[$relPrefix] = $relDAO->contact_id
;
502 elseif (is_array($relationValue) && $relationField == 'location') {
503 foreach ($relationValue as $ltype => $val) {
504 // If the location name has a space in it the we need to handle that. This
505 // is kinda hacky but specifically covered in the ExportTest so later efforts to
506 // improve it should be secure in the knowled it will be caught.
507 $ltype = str_replace(' ', '_', $ltype);
508 foreach (array_keys($val) as $fld) {
509 $type = explode('-', $fld);
510 $fldValue = "{$ltype}-" . $type[0];
511 if (!empty($type[1])) {
512 $fldValue .= "-" . $type[1];
514 // CRM-3157: localise country, region (both have ‘country’ context)
515 // and state_province (‘province’ context)
517 case (!is_object($relDAO)):
518 $row[$field . '_' . $fldValue] = '';
521 case in_array('country', $type):
522 case in_array('world_region', $type):
523 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
524 ['context' => 'country']
528 case in_array('state_province', $type):
529 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
530 ['context' => 'province']
535 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
541 elseif (isset($fieldValue) && $fieldValue != '') {
542 //check for custom data
543 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($relationField)) {
544 $row[$relPrefix] = CRM_Core_BAO_CustomField
::displayValue($fieldValue, $cfID);
547 //normal relationship fields
548 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
549 switch ($relationField) {
552 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
555 case 'state_province':
556 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
560 $row[$relPrefix] = $fieldValue;
566 // if relation field is empty or null
567 $row[$relPrefix] = '';
573 * Get the ids that we want to get related contact details for.
576 * @param int $exportMode
580 protected static function getIDsForRelatedContact($ids, $exportMode) {
581 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
584 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
586 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
587 $dao = CRM_Core_DAO
::executeQuery("
588 SELECT contact_id FROM civicrm_activity_contact
589 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
590 record_type_id = {$sourceID}
593 while ($dao->fetch()) {
594 $relIDs[] = $dao->contact_id
;
598 $component = self
::exportComponent($exportMode);
600 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
601 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
604 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $component);
611 * @param \CRM_Export_BAO_ExportProcessor $processor
612 * @param $componentTable
614 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
615 $allRelContactArray = $relationQuery = [];
616 $queryMode = $processor->getQueryMode();
617 $exportMode = $processor->getExportMode();
619 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
620 $allRelContactArray[$relationshipKey] = [];
621 // build Query for each relationship
622 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
623 NULL, FALSE, FALSE, $queryMode
625 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
627 list($id, $direction) = explode('_', $relationshipKey, 2);
628 // identify the relationship direction
629 $contactA = 'contact_id_a';
630 $contactB = 'contact_id_b';
631 if ($direction == 'b_a') {
632 $contactA = 'contact_id_b';
633 $contactB = 'contact_id_a';
635 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
637 $relationshipJoin = $relationshipClause = '';
638 if (!$selectAll && $componentTable) {
639 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
641 elseif (!empty($relIDs)) {
642 $relID = implode(',', $relIDs);
643 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
646 $relationFrom = " {$relationFrom}
647 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
648 {$relationshipJoin} ";
650 //check for active relationship status only
651 $today = date('Ymd');
652 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
653 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
654 CRM_Core_DAO
::disableFullGroupByMode();
655 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
656 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
658 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
659 CRM_Core_DAO
::reenableFullGroupByMode();
661 while ($allRelContactDAO->fetch()) {
662 $relationQuery->convertToPseudoNames($allRelContactDAO);
664 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
665 self
::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
666 foreach (array_keys($relationReturnProperties) as $property) {
667 if ($property === 'location') {
668 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
669 // $processor->setRelationshipValue from fetchRelationshipDetails
670 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
671 foreach (array_keys($locationValues) as $locationValue) {
672 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
673 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
678 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);