3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * This class contains the functions for Component export
22 class CRM_Export_BAO_Export
{
23 // increase this number a lot to avoid making too many queries
24 // LIMIT is not much faster than a no LIMIT query
26 const EXPORT_ROW_COUNT
= 100000;
29 * Get the list the export fields.
31 * @param int $selectAll
32 * User preference while export.
35 * @param array $params
36 * Associated array of fields.
37 * @param string $order
39 * @param array $fields
40 * Associated array of fields.
41 * @param array $moreReturnProperties
42 * Additional return fields.
43 * @param int $exportMode
45 * @param string $componentClause
47 * @param string $componentTable
49 * @param bool $mergeSameAddress
50 * Merge records if they have same address.
51 * @param bool $mergeSameHousehold
52 * Merge records if they belong to the same household.
54 * @param array $exportParams
55 * @param string $queryOperator
57 * @throws \CRM_Core_Exception
59 public static function exportComponents(
65 $moreReturnProperties = NULL,
66 $exportMode = CRM_Export_Form_Select
::CONTACT_EXPORT
,
67 $componentClause = NULL,
68 $componentTable = NULL,
69 $mergeSameAddress = FALSE,
70 $mergeSameHousehold = FALSE,
72 $queryOperator = 'AND'
76 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
77 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
80 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
81 // If an Additional Group is selected, then all contacts in that group are
82 // added to the export set (filtering out duplicates).
83 // Really - the calling function could do this ... just saying
84 // @todo take a whip to the calling function.
85 CRM_Core_DAO
::executeQuery("
86 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"
89 // rectify params to what proximity search expects if there is a value for prox_distance
91 // @todo - move this back to the calling functions
92 if (!empty($params)) {
93 CRM_Contact_BAO_ProximityQuery
::fixInputParams($params);
95 // @todo everything from this line up should go back to the calling functions.
96 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress, $exportParams);
97 if ($moreReturnProperties) {
98 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
100 $processor->setComponentTable($componentTable);
101 $processor->setComponentClause($componentClause);
102 $processor->setIds($ids);
104 list($query, $queryString) = $processor->runQuery($params, $order);
106 // This perhaps only needs calling when $mergeSameHousehold == 1
107 self
::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
109 $addPaymentHeader = FALSE;
111 list($outputColumns, $metadata) = $processor->getExportStructureArrays();
113 if ($processor->isMergeSameAddress()) {
114 foreach (array_keys($processor->getAdditionalFieldsForSameAddressMerge()) as $field) {
115 if ($field === 'id') {
116 $field = 'civicrm_primary_id';
118 $processor->setColumnAsCalculationOnly($field);
122 $paymentDetails = [];
123 if ($processor->isExportPaymentFields()) {
124 // get payment related in for event and members
125 $paymentDetails = CRM_Contribute_BAO_Contribution
::getContributionDetails($exportMode, $ids);
126 //get all payment headers.
127 // If we haven't selected specific payment fields, load in all the
129 if (!$processor->isExportSpecifiedPaymentFields()) {
130 if (!empty($paymentDetails)) {
131 $addPaymentHeader = TRUE;
132 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
133 $processor->addOutputSpecification($paymentField);
139 $componentDetails = [];
141 $rowCount = self
::EXPORT_ROW_COUNT
;
143 // we write to temp table often to avoid using too much memory
148 $sqlColumns = $processor->getSQLColumns();
149 $processor->createTempTable();
150 $limitReached = FALSE;
152 while (!$limitReached) {
153 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
154 CRM_Core_DAO
::disableFullGroupByMode();
155 $iterationDAO = CRM_Core_DAO
::executeQuery($limitQuery);
156 CRM_Core_DAO
::reenableFullGroupByMode();
157 // If this is less than our limit by the end of the iteration we do not need to run the query again to
158 // check if some remain.
159 $rowsThisIteration = 0;
161 while ($iterationDAO->fetch()) {
163 $rowsThisIteration++
;
164 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader);
165 if ($row === FALSE) {
169 // add component info
170 // write the row to a file
171 $componentDetails[] = $row;
173 // output every $tempRowCount rows
174 if ($count %
$tempRowCount == 0) {
175 self
::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
176 $componentDetails = [];
179 if ($rowsThisIteration < self
::EXPORT_ROW_COUNT
) {
180 $limitReached = TRUE;
182 $offset +
= $rowCount;
185 if ($processor->getTemporaryTable()) {
186 self
::writeDetailsToTable($processor, $componentDetails);
188 // do merge same address and merge same household processing
189 if ($mergeSameAddress) {
190 $processor->mergeSameAddress();
193 $processor->writeCSVFromTable();
195 // delete the export temp table and component table
196 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
197 CRM_Core_DAO
::executeQuery($sql);
198 CRM_Core_DAO
::reenableFullGroupByMode();
199 CRM_Utils_System
::civiExit(0, ['processor' => $processor]);
202 CRM_Core_DAO
::reenableFullGroupByMode();
203 throw new CRM_Core_Exception(ts('No records to export'));
208 * Handle import error file creation.
210 public static function invoke() {
211 $type = CRM_Utils_Request
::retrieve('type', 'Positive');
212 $parserName = CRM_Utils_Request
::retrieve('parser', 'String');
213 if (empty($parserName) ||
empty($type)) {
217 // clean and ensure parserName is a valid string
218 $parserName = CRM_Utils_String
::munge($parserName);
219 $parserClass = explode('_', $parserName);
221 // make sure parserClass is in the CRM namespace and
222 // at least 3 levels deep
223 if ($parserClass[0] == 'CRM' &&
224 count($parserClass) >= 3
226 require_once str_replace('_', DIRECTORY_SEPARATOR
, $parserName) . ".php";
227 // ensure the functions exists
228 if (method_exists($parserName, 'errorFileName') &&
229 method_exists($parserName, 'saveFileName')
231 $errorFileName = $parserName::errorFileName($type);
232 $saveFileName = $parserName::saveFileName($type);
233 if (!empty($errorFileName) && !empty($saveFileName)) {
234 CRM_Utils_System
::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
235 CRM_Utils_System
::setHttpHeader('Content-Description', 'File Transfer');
236 CRM_Utils_System
::setHttpHeader('Content-Type', 'text/csv');
237 CRM_Utils_System
::setHttpHeader('Content-Length', filesize($errorFileName));
238 CRM_Utils_System
::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
240 readfile($errorFileName);
244 CRM_Utils_System
::civiExit();
248 * @param $customSearchClass
252 public static function exportCustom($customSearchClass, $formValues, $order) {
253 $ext = CRM_Extension_System
::singleton()->getMapper();
254 if (!$ext->isExtensionClass($customSearchClass)) {
255 require_once str_replace('_', DIRECTORY_SEPARATOR
, $customSearchClass) . '.php';
258 require_once $ext->classToPath($customSearchClass);
260 $search = new $customSearchClass($formValues);
262 $includeContactIDs = FALSE;
263 if ($formValues['radio_ts'] == 'ts_sel') {
264 $includeContactIDs = TRUE;
267 $sql = $search->all(0, 0, $order, $includeContactIDs);
269 $columns = $search->columns();
271 $header = array_keys($columns);
272 $fields = array_values($columns);
275 $dao = CRM_Core_DAO
::executeQuery($sql);
277 if (method_exists($search, 'alterRow')) {
280 while ($dao->fetch()) {
283 foreach ($fields as $field) {
284 $unqualified_field = CRM_Utils_Array
::First(array_slice(explode('.', $field), -1));
285 $row[$field] = $dao->$unqualified_field;
288 $search->alterRow($row);
293 CRM_Core_Report_Excel
::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
294 CRM_Utils_System
::civiExit();
298 * @param \CRM_Export_BAO_ExportProcessor $processor
301 public static function writeDetailsToTable($processor, $details) {
302 $tableName = $processor->getTemporaryTable();
303 if (empty($details)) {
312 $id = CRM_Core_DAO
::singleValueQuery($sql);
319 foreach ($details as $row) {
321 $valueString = [$id];
322 foreach ($row as $value) {
324 $valueString[] = "''";
327 $valueString[] = "'" . CRM_Core_DAO
::escapeString($value) . "'";
330 $sqlClause[] = '(' . implode(',', $valueString) . ')';
332 $sqlColumns = array_merge(['id' => 1], $processor->getSQLColumns());
333 $sqlColumnString = '(`' . implode('`, `', array_keys($sqlColumns)) . '`)';
335 $sqlValueString = implode(",\n", $sqlClause);
338 INSERT INTO $tableName $sqlColumnString
339 VALUES $sqlValueString
341 CRM_Core_DAO
::executeQuery($sql);
345 * Get the ids that we want to get related contact details for.
348 * @param int $exportMode
352 protected static function getIDsForRelatedContact($ids, $exportMode) {
353 if ($exportMode == CRM_Export_Form_Select
::CONTACT_EXPORT
) {
356 if ($exportMode == CRM_Export_Form_Select
::ACTIVITY_EXPORT
) {
358 $sourceID = CRM_Core_PseudoConstant
::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
359 $dao = CRM_Core_DAO
::executeQuery("
360 SELECT contact_id FROM civicrm_activity_contact
361 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
362 record_type_id = {$sourceID}
365 while ($dao->fetch()) {
366 $relIDs[] = $dao->contact_id
;
370 $componentMapping = [
371 CRM_Export_Form_Select
::CONTRIBUTE_EXPORT
=> 'civicrm_contribution',
372 CRM_Export_Form_Select
::EVENT_EXPORT
=> 'civicrm_participant',
373 CRM_Export_Form_Select
::MEMBER_EXPORT
=> 'civicrm_membership',
374 CRM_Export_Form_Select
::PLEDGE_EXPORT
=> 'civicrm_pledge',
375 CRM_Export_Form_Select
::GRANT_EXPORT
=> 'civicrm_grant',
378 if ($exportMode == CRM_Export_Form_Select
::CASE_EXPORT
) {
379 return CRM_Case_BAO_Case
::retrieveContactIdsByCaseId($ids);
382 return CRM_Core_DAO
::getContactIDsFromComponent($ids, $componentMapping[$exportMode]);
389 * @param \CRM_Export_BAO_ExportProcessor $processor
390 * @param $componentTable
392 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
393 $allRelContactArray = $relationQuery = [];
394 $queryMode = $processor->getQueryMode();
395 $exportMode = $processor->getExportMode();
397 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
398 $allRelContactArray[$relationshipKey] = [];
399 // build Query for each relationship
400 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
401 NULL, FALSE, FALSE, $queryMode
403 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
405 list($id, $direction) = explode('_', $relationshipKey, 2);
406 // identify the relationship direction
407 $contactA = 'contact_id_a';
408 $contactB = 'contact_id_b';
409 if ($direction == 'b_a') {
410 $contactA = 'contact_id_b';
411 $contactB = 'contact_id_a';
413 $relIDs = self
::getIDsForRelatedContact($ids, $exportMode);
415 $relationshipJoin = $relationshipClause = '';
416 if (!$selectAll && $componentTable) {
417 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
419 elseif (!empty($relIDs)) {
420 $relID = implode(',', $relIDs);
421 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
424 $relationFrom = " {$relationFrom}
425 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
426 {$relationshipJoin} ";
428 //check for active relationship status only
429 $today = date('Ymd');
430 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
431 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
432 CRM_Core_DAO
::disableFullGroupByMode();
433 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
434 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
436 $allRelContactDAO = CRM_Core_DAO
::executeQuery($relationQueryString);
437 CRM_Core_DAO
::reenableFullGroupByMode();
439 while ($allRelContactDAO->fetch()) {
440 $relationQuery->convertToPseudoNames($allRelContactDAO);
442 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
443 $processor->fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
444 foreach (array_keys($relationReturnProperties) as $property) {
445 if ($property === 'location') {
446 // @todo - simplify location in fetchRelationshipDetails - remove handling here. Or just call
447 // $processor->setRelationshipValue from fetchRelationshipDetails
448 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
449 foreach (array_keys($locationValues) as $locationValue) {
450 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
451 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $key, $row[$relationshipKey . '__' . $key]);
456 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact
, $property, $row[$relationshipKey . '_' . $property]);