Merge pull request #14913 from eileenmcnaughton/export
[civicrm-core.git] / CRM / Export / BAO / Export.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 */
33
34/**
748450ad 35 * This class contains the functions for Component export
6a488035
TO
36 *
37 */
38class 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
41 // CRM-7675
24c7dffa 42 const EXPORT_ROW_COUNT = 100000;
6a488035
TO
43
44 /**
fe482240 45 * Get the list the export fields.
6a488035 46 *
b9add4b3
TO
47 * @param int $selectAll
48 * User preference while export.
49 * @param array $ids
50 * Contact ids.
51 * @param array $params
52 * Associated array of fields.
53 * @param string $order
54 * Order by clause.
55 * @param array $fields
56 * Associated array of fields.
57 * @param array $moreReturnProperties
58 * Additional return fields.
59 * @param int $exportMode
60 * Export mode.
61 * @param string $componentClause
62 * Component clause.
63 * @param string $componentTable
64 * Component table.
65 * @param bool $mergeSameAddress
66 * Merge records if they have same address.
67 * @param bool $mergeSameHousehold
68 * Merge records if they belong to the same household.
6c8f6e67
EM
69 *
70 * @param array $exportParams
71 * @param string $queryOperator
6a488035 72 *
c7224305 73 * @return array|null
74 * An array can be requested from within a unit test.
75 *
76 * @throws \CRM_Core_Exception
6a488035 77 */
317fceb4 78 public static function exportComponents(
97f6897c 79 $selectAll,
6a488035
TO
80 $ids,
81 $params,
82 $order = NULL,
83 $fields = NULL,
84 $moreReturnProperties = NULL,
85 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
86 $componentClause = NULL,
87 $componentTable = NULL,
88 $mergeSameAddress = FALSE,
89 $mergeSameHousehold = FALSE,
be2fb01f 90 $exportParams = [],
6a488035
TO
91 $queryOperator = 'AND'
92 ) {
ef51caa8 93
6d52bfe5 94 $isPostalOnly = (
95 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
96 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
97 );
98
7d6dd61c 99 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
100 // If an Additional Group is selected, then all contacts in that group are
101 // added to the export set (filtering out duplicates).
102 // Really - the calling function could do this ... just saying
103 // @todo take a whip to the calling function.
104 CRM_Core_DAO::executeQuery("
105INSERT 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"
106 );
107 }
9e49a7b8
PJ
108 // rectify params to what proximity search expects if there is a value for prox_distance
109 // CRM-7021
3c6340a6 110 // @todo - move this back to the calling functions
9e49a7b8
PJ
111 if (!empty($params)) {
112 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
113 }
3c6340a6 114 // @todo everything from this line up should go back to the calling functions.
1e9e062d 115 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress, $exportParams);
3c6340a6 116 if ($moreReturnProperties) {
117 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
118 }
e034ee91 119 $processor->setComponentTable($componentTable);
120 $processor->setComponentClause($componentClause);
9e49a7b8 121
9858dc0b 122 list($query, $queryString) = $processor->runQuery($params, $order);
6a488035 123
ebebd629 124 // This perhaps only needs calling when $mergeSameHousehold == 1
ce12a9e0 125 self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
6a488035 126
6a488035
TO
127 $addPaymentHeader = FALSE;
128
44fc53ab 129 list($outputColumns, $metadata) = $processor->getExportStructureArrays();
943e6943 130
7e2ee2fb 131 if ($processor->isMergeSameAddress()) {
f8fb0608 132 foreach (array_keys($processor->getAdditionalFieldsForSameAddressMerge()) as $field) {
c8925481 133 $processor->setColumnAsCalculationOnly($field);
134 }
135 }
136
943e6943 137 $paymentDetails = [];
c66a5741 138 if ($processor->isExportPaymentFields()) {
6a488035
TO
139 // get payment related in for event and members
140 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
d77aba4b 141 //get all payment headers.
7460c131
AS
142 // If we haven't selected specific payment fields, load in all the
143 // payment headers.
c66a5741 144 if (!$processor->isExportSpecifiedPaymentFields()) {
d77aba4b
AS
145 if (!empty($paymentDetails)) {
146 $addPaymentHeader = TRUE;
943e6943 147 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
148 $processor->addOutputSpecification($paymentField);
149 }
d77aba4b 150 }
6a488035 151 }
6a488035
TO
152 }
153
be2fb01f 154 $componentDetails = [];
6a488035
TO
155
156 $rowCount = self::EXPORT_ROW_COUNT;
157 $offset = 0;
158 // we write to temp table often to avoid using too much memory
159 $tempRowCount = 100;
160
161 $count = -1;
162
2cd3d767 163 $sqlColumns = $processor->getSQLColumns();
3e644436 164 $processor->createTempTable();
24c7dffa 165 $limitReached = FALSE;
0b94b406 166
24c7dffa 167 while (!$limitReached) {
6a488035 168 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
6f5824c1 169 CRM_Core_DAO::disableFullGroupByMode();
bab4f15e 170 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
6f5824c1 171 CRM_Core_DAO::reenableFullGroupByMode();
24c7dffa 172 // If this is less than our limit by the end of the iteration we do not need to run the query again to
173 // check if some remain.
174 $rowsThisIteration = 0;
6a488035 175
bab4f15e 176 while ($iterationDAO->fetch()) {
6a488035 177 $count++;
24c7dffa 178 $rowsThisIteration++;
c58085f8 179 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader);
136f69a8 180 if ($row === FALSE) {
181 continue;
182 }
6a488035
TO
183
184 // add component info
185 // write the row to a file
186 $componentDetails[] = $row;
187
188 // output every $tempRowCount rows
189 if ($count % $tempRowCount == 0) {
68989e71 190 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
be2fb01f 191 $componentDetails = [];
6a488035
TO
192 }
193 }
24c7dffa 194 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
195 $limitReached = TRUE;
196 }
6a488035
TO
197 $offset += $rowCount;
198 }
199
68989e71 200 if ($processor->getTemporaryTable()) {
c33484c7 201 self::writeDetailsToTable($processor, $componentDetails);
6a488035
TO
202
203 // do merge same address and merge same household processing
204 if ($mergeSameAddress) {
f8fb0608 205 $processor->mergeSameAddress();
6a488035
TO
206 }
207
ef51caa8 208 // In order to be able to write a unit test against this function we need to suppress
209 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
210 if (empty($exportParams['suppress_csv_for_testing'])) {
639046e8 211 self::writeCSVFromTable($processor);
ef51caa8 212 }
994a070c 213 else {
b7db6051 214 // return tableName sqlColumns headerRows in test context
639046e8 215 return [$processor->getTemporaryTable(), $sqlColumns, $processor->getHeaderRows(), $processor];
994a070c 216 }
6a488035
TO
217
218 // delete the export temp table and component table
68989e71 219 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
6a488035 220 CRM_Core_DAO::executeQuery($sql);
2f68ef20 221 CRM_Core_DAO::reenableFullGroupByMode();
68989e71 222 CRM_Utils_System::civiExit(0, ['processor' => $processor]);
6a488035
TO
223 }
224 else {
2f68ef20 225 CRM_Core_DAO::reenableFullGroupByMode();
c7224305 226 throw new CRM_Core_Exception(ts('No records to export'));
6a488035
TO
227 }
228 }
229
6a488035 230 /**
100fef9d 231 * Handle import error file creation.
6a488035 232 */
00be9182 233 public static function invoke() {
a3d827a7
CW
234 $type = CRM_Utils_Request::retrieve('type', 'Positive');
235 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
6a488035
TO
236 if (empty($parserName) || empty($type)) {
237 return;
238 }
239
240 // clean and ensure parserName is a valid string
241 $parserName = CRM_Utils_String::munge($parserName);
242 $parserClass = explode('_', $parserName);
243
244 // make sure parserClass is in the CRM namespace and
245 // at least 3 levels deep
246 if ($parserClass[0] == 'CRM' &&
247 count($parserClass) >= 3
248 ) {
d3e86119 249 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
6a488035
TO
250 // ensure the functions exists
251 if (method_exists($parserName, 'errorFileName') &&
252 method_exists($parserName, 'saveFileName')
253 ) {
254 $errorFileName = $parserName::errorFileName($type);
255 $saveFileName = $parserName::saveFileName($type);
256 if (!empty($errorFileName) && !empty($saveFileName)) {
d42a224c
CW
257 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
258 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
259 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
260 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
261 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
6a488035
TO
262
263 readfile($errorFileName);
264 }
265 }
266 }
267 CRM_Utils_System::civiExit();
268 }
269
e0ef6999
EM
270 /**
271 * @param $customSearchClass
272 * @param $formValues
273 * @param $order
274 */
00be9182 275 public static function exportCustom($customSearchClass, $formValues, $order) {
6a488035
TO
276 $ext = CRM_Extension_System::singleton()->getMapper();
277 if (!$ext->isExtensionClass($customSearchClass)) {
d3e86119 278 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
6a488035
TO
279 }
280 else {
d3e86119 281 require_once $ext->classToPath($customSearchClass);
6a488035
TO
282 }
283 $search = new $customSearchClass($formValues);
284
285 $includeContactIDs = FALSE;
286 if ($formValues['radio_ts'] == 'ts_sel') {
287 $includeContactIDs = TRUE;
288 }
289
290 $sql = $search->all(0, 0, $order, $includeContactIDs);
291
292 $columns = $search->columns();
293
294 $header = array_keys($columns);
295 $fields = array_values($columns);
296
be2fb01f 297 $rows = [];
97f6897c 298 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
299 $alterRow = FALSE;
300 if (method_exists($search, 'alterRow')) {
301 $alterRow = TRUE;
302 }
303 while ($dao->fetch()) {
be2fb01f 304 $row = [];
6a488035
TO
305
306 foreach ($fields as $field) {
37990ecd
JV
307 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
308 $row[$field] = $dao->$unqualified_field;
6a488035
TO
309 }
310 if ($alterRow) {
311 $search->alterRow($row);
312 }
313 $rows[] = $row;
314 }
315
620eae15 316 CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
6a488035
TO
317 CRM_Utils_System::civiExit();
318 }
319
e0ef6999 320 /**
68989e71 321 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999 322 * @param $details
e0ef6999 323 */
c33484c7 324 public static function writeDetailsToTable($processor, $details) {
68989e71 325 $tableName = $processor->getTemporaryTable();
6a488035
TO
326 if (empty($details)) {
327 return;
328 }
329
330 $sql = "
331SELECT max(id)
332FROM $tableName
333";
334
335 $id = CRM_Core_DAO::singleValueQuery($sql);
336 if (!$id) {
337 $id = 0;
338 }
339
be2fb01f 340 $sqlClause = [];
6a488035 341
610f72e1 342 foreach ($details as $row) {
6a488035 343 $id++;
be2fb01f 344 $valueString = [$id];
610f72e1 345 foreach ($row as $value) {
6a488035
TO
346 if (empty($value)) {
347 $valueString[] = "''";
348 }
349 else {
350 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
351 }
352 }
353 $sqlClause[] = '(' . implode(',', $valueString) . ')';
354 }
c33484c7 355 $sqlColumns = array_merge(['id' => 1], $processor->getSQLColumns());
dfab581c 356 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
6a488035
TO
357
358 $sqlValueString = implode(",\n", $sqlClause);
359
360 $sql = "
361INSERT INTO $tableName $sqlColumnString
362VALUES $sqlValueString
363";
6a488035
TO
364 CRM_Core_DAO::executeQuery($sql);
365 }
366
e0ef6999 367 /**
70107611 368 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999 369 */
639046e8 370 public static function writeCSVFromTable($processor) {
371 // call export hook
372 $headerRows = $processor->getHeaderRows();
373 $exportTempTable = $processor->getTemporaryTable();
374 CRM_Utils_Hook::export($exportTempTable, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
375 if ($exportTempTable !== $processor->getTemporaryTable()) {
376 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
377 $processor->setTemporaryTable($exportTempTable);
378 }
68989e71 379 $exportTempTable = $processor->getTemporaryTable();
6a488035 380 $writeHeader = TRUE;
97f6897c
TO
381 $offset = 0;
382 $limit = self::EXPORT_ROW_COUNT;
6a488035
TO
383
384 $query = "SELECT * FROM $exportTempTable";
385
386 while (1) {
387 $limitQuery = $query . "
388LIMIT $offset, $limit
389";
390 $dao = CRM_Core_DAO::executeQuery($limitQuery);
391
392 if ($dao->N <= 0) {
393 break;
394 }
395
be2fb01f 396 $componentDetails = [];
6a488035 397 while ($dao->fetch()) {
be2fb01f 398 $row = [];
6a488035 399
f8fb0608 400 foreach (array_keys($processor->getSQLColumns()) as $column) {
6a488035
TO
401 $row[$column] = $dao->$column;
402 }
403 $componentDetails[] = $row;
404 }
29034a98 405 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
6a488035
TO
406 $headerRows,
407 $componentDetails,
97f6897c 408 NULL,
70107611 409 $writeHeader
410 );
6a488035 411
97f6897c 412 $writeHeader = FALSE;
6a488035
TO
413 $offset += $limit;
414 }
415 }
416
814065a3 417 /**
418 * Get the ids that we want to get related contact details for.
419 *
420 * @param array $ids
421 * @param int $exportMode
422 *
423 * @return array
424 */
425 protected static function getIDsForRelatedContact($ids, $exportMode) {
426 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
427 return $ids;
428 }
429 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
430 $relIDs = [];
431 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
432 $dao = CRM_Core_DAO::executeQuery("
433 SELECT contact_id FROM civicrm_activity_contact
434 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
435 record_type_id = {$sourceID}
436 ");
437
438 while ($dao->fetch()) {
439 $relIDs[] = $dao->contact_id;
440 }
441 return $relIDs;
442 }
323390ce 443 $componentMapping = [
444 CRM_Export_Form_Select::CONTRIBUTE_EXPORT => 'civicrm_contribution',
445 CRM_Export_Form_Select::EVENT_EXPORT => 'civicrm_participant',
446 CRM_Export_Form_Select::MEMBER_EXPORT => 'civicrm_membership',
447 CRM_Export_Form_Select::PLEDGE_EXPORT => 'civicrm_pledge',
448 CRM_Export_Form_Select::GRANT_EXPORT => 'civicrm_grant',
449 ];
814065a3 450
451 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
452 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
453 }
454 else {
323390ce 455 return CRM_Core_DAO::getContactIDsFromComponent($ids, $componentMapping[$exportMode]);
814065a3 456 }
457 }
458
44f8f95c 459 /**
460 * @param $selectAll
461 * @param $ids
439355f5 462 * @param \CRM_Export_BAO_ExportProcessor $processor
44f8f95c 463 * @param $componentTable
44f8f95c 464 */
ce12a9e0 465 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
be2fb01f 466 $allRelContactArray = $relationQuery = [];
439355f5 467 $queryMode = $processor->getQueryMode();
468 $exportMode = $processor->getExportMode();
44f8f95c 469
ce12a9e0 470 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
be2fb01f 471 $allRelContactArray[$relationshipKey] = [];
ce12a9e0 472 // build Query for each relationship
473 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
474 NULL, FALSE, FALSE, $queryMode
475 );
476 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
477
478 list($id, $direction) = explode('_', $relationshipKey, 2);
479 // identify the relationship direction
480 $contactA = 'contact_id_a';
481 $contactB = 'contact_id_b';
482 if ($direction == 'b_a') {
483 $contactA = 'contact_id_b';
484 $contactB = 'contact_id_a';
485 }
486 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
487
488 $relationshipJoin = $relationshipClause = '';
489 if (!$selectAll && $componentTable) {
490 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
491 }
492 elseif (!empty($relIDs)) {
493 $relID = implode(',', $relIDs);
494 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
495 }
44f8f95c 496
ce12a9e0 497 $relationFrom = " {$relationFrom}
498 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
499 {$relationshipJoin} ";
500
501 //check for active relationship status only
502 $today = date('Ymd');
503 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
504 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
6f5824c1 505 CRM_Core_DAO::disableFullGroupByMode();
ce12a9e0 506 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
6f5824c1 507 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
ce12a9e0 508
509 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
6f5824c1 510 CRM_Core_DAO::reenableFullGroupByMode();
511
ce12a9e0 512 while ($allRelContactDAO->fetch()) {
513 $relationQuery->convertToPseudoNames($allRelContactDAO);
514 $row = [];
515 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
b0b40cd7 516 $processor->fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
ce12a9e0 517 foreach (array_keys($relationReturnProperties) as $property) {
518 if ($property === 'location') {
b0b40cd7 519 // @todo - simplify location in fetchRelationshipDetails - remove handling here. Or just call
ce12a9e0 520 // $processor->setRelationshipValue from fetchRelationshipDetails
521 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
522 foreach (array_keys($locationValues) as $locationValue) {
523 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
524 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
525 }
526 }
527 }
528 else {
529 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
530 }
44f8f95c 531 }
44f8f95c 532 }
533 }
44f8f95c 534 }
535
6a488035 536}