Move fetch Relationship details to processor
[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
28254dcb 163 $headerRows = $processor->getHeaderRows();
2cd3d767 164 $sqlColumns = $processor->getSQLColumns();
3e644436 165 $processor->createTempTable();
24c7dffa 166 $limitReached = FALSE;
0b94b406 167
24c7dffa 168 while (!$limitReached) {
6a488035 169 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
6f5824c1 170 CRM_Core_DAO::disableFullGroupByMode();
bab4f15e 171 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
6f5824c1 172 CRM_Core_DAO::reenableFullGroupByMode();
24c7dffa 173 // If this is less than our limit by the end of the iteration we do not need to run the query again to
174 // check if some remain.
175 $rowsThisIteration = 0;
6a488035 176
bab4f15e 177 while ($iterationDAO->fetch()) {
6a488035 178 $count++;
24c7dffa 179 $rowsThisIteration++;
c58085f8 180 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader);
136f69a8 181 if ($row === FALSE) {
182 continue;
183 }
6a488035
TO
184
185 // add component info
186 // write the row to a file
187 $componentDetails[] = $row;
188
189 // output every $tempRowCount rows
190 if ($count % $tempRowCount == 0) {
68989e71 191 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
be2fb01f 192 $componentDetails = [];
6a488035
TO
193 }
194 }
24c7dffa 195 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
196 $limitReached = TRUE;
197 }
6a488035
TO
198 $offset += $rowCount;
199 }
200
68989e71 201 if ($processor->getTemporaryTable()) {
c33484c7 202 self::writeDetailsToTable($processor, $componentDetails);
6a488035
TO
203
204 // do merge same address and merge same household processing
205 if ($mergeSameAddress) {
f8fb0608 206 $processor->mergeSameAddress();
6a488035
TO
207 }
208
6a488035 209 // call export hook
68989e71 210 $table = $processor->getTemporaryTable();
211 CRM_Utils_Hook::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
212 if ($table !== $processor->getTemporaryTable()) {
213 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
214 $processor->setTemporaryTable($table);
215 }
6a488035 216
ef51caa8 217 // In order to be able to write a unit test against this function we need to suppress
218 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
219 if (empty($exportParams['suppress_csv_for_testing'])) {
68989e71 220 self::writeCSVFromTable($headerRows, $sqlColumns, $processor);
ef51caa8 221 }
994a070c 222 else {
b7db6051 223 // return tableName sqlColumns headerRows in test context
68989e71 224 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
994a070c 225 }
6a488035
TO
226
227 // delete the export temp table and component table
68989e71 228 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
6a488035 229 CRM_Core_DAO::executeQuery($sql);
2f68ef20 230 CRM_Core_DAO::reenableFullGroupByMode();
68989e71 231 CRM_Utils_System::civiExit(0, ['processor' => $processor]);
6a488035
TO
232 }
233 else {
2f68ef20 234 CRM_Core_DAO::reenableFullGroupByMode();
c7224305 235 throw new CRM_Core_Exception(ts('No records to export'));
6a488035
TO
236 }
237 }
238
6a488035 239 /**
100fef9d 240 * Handle import error file creation.
6a488035 241 */
00be9182 242 public static function invoke() {
a3d827a7
CW
243 $type = CRM_Utils_Request::retrieve('type', 'Positive');
244 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
6a488035
TO
245 if (empty($parserName) || empty($type)) {
246 return;
247 }
248
249 // clean and ensure parserName is a valid string
250 $parserName = CRM_Utils_String::munge($parserName);
251 $parserClass = explode('_', $parserName);
252
253 // make sure parserClass is in the CRM namespace and
254 // at least 3 levels deep
255 if ($parserClass[0] == 'CRM' &&
256 count($parserClass) >= 3
257 ) {
d3e86119 258 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
6a488035
TO
259 // ensure the functions exists
260 if (method_exists($parserName, 'errorFileName') &&
261 method_exists($parserName, 'saveFileName')
262 ) {
263 $errorFileName = $parserName::errorFileName($type);
264 $saveFileName = $parserName::saveFileName($type);
265 if (!empty($errorFileName) && !empty($saveFileName)) {
d42a224c
CW
266 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
267 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
268 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
269 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
270 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
6a488035
TO
271
272 readfile($errorFileName);
273 }
274 }
275 }
276 CRM_Utils_System::civiExit();
277 }
278
e0ef6999
EM
279 /**
280 * @param $customSearchClass
281 * @param $formValues
282 * @param $order
283 */
00be9182 284 public static function exportCustom($customSearchClass, $formValues, $order) {
6a488035
TO
285 $ext = CRM_Extension_System::singleton()->getMapper();
286 if (!$ext->isExtensionClass($customSearchClass)) {
d3e86119 287 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
6a488035
TO
288 }
289 else {
d3e86119 290 require_once $ext->classToPath($customSearchClass);
6a488035
TO
291 }
292 $search = new $customSearchClass($formValues);
293
294 $includeContactIDs = FALSE;
295 if ($formValues['radio_ts'] == 'ts_sel') {
296 $includeContactIDs = TRUE;
297 }
298
299 $sql = $search->all(0, 0, $order, $includeContactIDs);
300
301 $columns = $search->columns();
302
303 $header = array_keys($columns);
304 $fields = array_values($columns);
305
be2fb01f 306 $rows = [];
97f6897c 307 $dao = CRM_Core_DAO::executeQuery($sql);
6a488035
TO
308 $alterRow = FALSE;
309 if (method_exists($search, 'alterRow')) {
310 $alterRow = TRUE;
311 }
312 while ($dao->fetch()) {
be2fb01f 313 $row = [];
6a488035
TO
314
315 foreach ($fields as $field) {
37990ecd
JV
316 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
317 $row[$field] = $dao->$unqualified_field;
6a488035
TO
318 }
319 if ($alterRow) {
320 $search->alterRow($row);
321 }
322 $rows[] = $row;
323 }
324
620eae15 325 CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
6a488035
TO
326 CRM_Utils_System::civiExit();
327 }
328
e0ef6999 329 /**
68989e71 330 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999 331 * @param $details
e0ef6999 332 */
c33484c7 333 public static function writeDetailsToTable($processor, $details) {
68989e71 334 $tableName = $processor->getTemporaryTable();
6a488035
TO
335 if (empty($details)) {
336 return;
337 }
338
339 $sql = "
340SELECT max(id)
341FROM $tableName
342";
343
344 $id = CRM_Core_DAO::singleValueQuery($sql);
345 if (!$id) {
346 $id = 0;
347 }
348
be2fb01f 349 $sqlClause = [];
6a488035 350
610f72e1 351 foreach ($details as $row) {
6a488035 352 $id++;
be2fb01f 353 $valueString = [$id];
610f72e1 354 foreach ($row as $value) {
6a488035
TO
355 if (empty($value)) {
356 $valueString[] = "''";
357 }
358 else {
359 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
360 }
361 }
362 $sqlClause[] = '(' . implode(',', $valueString) . ')';
363 }
c33484c7 364 $sqlColumns = array_merge(['id' => 1], $processor->getSQLColumns());
dfab581c 365 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
6a488035
TO
366
367 $sqlValueString = implode(",\n", $sqlClause);
368
369 $sql = "
370INSERT INTO $tableName $sqlColumnString
371VALUES $sqlValueString
372";
6a488035
TO
373 CRM_Core_DAO::executeQuery($sql);
374 }
375
e0ef6999 376 /**
e0ef6999
EM
377 * @param $headerRows
378 * @param $sqlColumns
70107611 379 * @param \CRM_Export_BAO_ExportProcessor $processor
e0ef6999 380 */
68989e71 381 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
382 $exportTempTable = $processor->getTemporaryTable();
6a488035 383 $writeHeader = TRUE;
97f6897c
TO
384 $offset = 0;
385 $limit = self::EXPORT_ROW_COUNT;
6a488035
TO
386
387 $query = "SELECT * FROM $exportTempTable";
388
389 while (1) {
390 $limitQuery = $query . "
391LIMIT $offset, $limit
392";
393 $dao = CRM_Core_DAO::executeQuery($limitQuery);
394
395 if ($dao->N <= 0) {
396 break;
397 }
398
be2fb01f 399 $componentDetails = [];
6a488035 400 while ($dao->fetch()) {
be2fb01f 401 $row = [];
6a488035 402
f8fb0608 403 foreach (array_keys($processor->getSQLColumns()) as $column) {
6a488035
TO
404 $row[$column] = $dao->$column;
405 }
406 $componentDetails[] = $row;
407 }
29034a98 408 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
6a488035
TO
409 $headerRows,
410 $componentDetails,
97f6897c 411 NULL,
70107611 412 $writeHeader
413 );
6a488035 414
97f6897c 415 $writeHeader = FALSE;
6a488035
TO
416 $offset += $limit;
417 }
418 }
419
814065a3 420 /**
421 * Get the ids that we want to get related contact details for.
422 *
423 * @param array $ids
424 * @param int $exportMode
425 *
426 * @return array
427 */
428 protected static function getIDsForRelatedContact($ids, $exportMode) {
429 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
430 return $ids;
431 }
432 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
433 $relIDs = [];
434 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
435 $dao = CRM_Core_DAO::executeQuery("
436 SELECT contact_id FROM civicrm_activity_contact
437 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
438 record_type_id = {$sourceID}
439 ");
440
441 while ($dao->fetch()) {
442 $relIDs[] = $dao->contact_id;
443 }
444 return $relIDs;
445 }
323390ce 446 $componentMapping = [
447 CRM_Export_Form_Select::CONTRIBUTE_EXPORT => 'civicrm_contribution',
448 CRM_Export_Form_Select::EVENT_EXPORT => 'civicrm_participant',
449 CRM_Export_Form_Select::MEMBER_EXPORT => 'civicrm_membership',
450 CRM_Export_Form_Select::PLEDGE_EXPORT => 'civicrm_pledge',
451 CRM_Export_Form_Select::GRANT_EXPORT => 'civicrm_grant',
452 ];
814065a3 453
454 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
455 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
456 }
457 else {
323390ce 458 return CRM_Core_DAO::getContactIDsFromComponent($ids, $componentMapping[$exportMode]);
814065a3 459 }
460 }
461
44f8f95c 462 /**
463 * @param $selectAll
464 * @param $ids
439355f5 465 * @param \CRM_Export_BAO_ExportProcessor $processor
44f8f95c 466 * @param $componentTable
44f8f95c 467 */
ce12a9e0 468 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
be2fb01f 469 $allRelContactArray = $relationQuery = [];
439355f5 470 $queryMode = $processor->getQueryMode();
471 $exportMode = $processor->getExportMode();
44f8f95c 472
ce12a9e0 473 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
be2fb01f 474 $allRelContactArray[$relationshipKey] = [];
ce12a9e0 475 // build Query for each relationship
476 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
477 NULL, FALSE, FALSE, $queryMode
478 );
479 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
480
481 list($id, $direction) = explode('_', $relationshipKey, 2);
482 // identify the relationship direction
483 $contactA = 'contact_id_a';
484 $contactB = 'contact_id_b';
485 if ($direction == 'b_a') {
486 $contactA = 'contact_id_b';
487 $contactB = 'contact_id_a';
488 }
489 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
490
491 $relationshipJoin = $relationshipClause = '';
492 if (!$selectAll && $componentTable) {
493 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
494 }
495 elseif (!empty($relIDs)) {
496 $relID = implode(',', $relIDs);
497 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
498 }
44f8f95c 499
ce12a9e0 500 $relationFrom = " {$relationFrom}
501 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
502 {$relationshipJoin} ";
503
504 //check for active relationship status only
505 $today = date('Ymd');
506 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
507 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
6f5824c1 508 CRM_Core_DAO::disableFullGroupByMode();
ce12a9e0 509 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
6f5824c1 510 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
ce12a9e0 511
512 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
6f5824c1 513 CRM_Core_DAO::reenableFullGroupByMode();
514
ce12a9e0 515 while ($allRelContactDAO->fetch()) {
516 $relationQuery->convertToPseudoNames($allRelContactDAO);
517 $row = [];
518 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
b0b40cd7 519 $processor->fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
ce12a9e0 520 foreach (array_keys($relationReturnProperties) as $property) {
521 if ($property === 'location') {
b0b40cd7 522 // @todo - simplify location in fetchRelationshipDetails - remove handling here. Or just call
ce12a9e0 523 // $processor->setRelationshipValue from fetchRelationshipDetails
524 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
525 foreach (array_keys($locationValues) as $locationValue) {
526 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
527 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
528 }
529 }
530 }
531 else {
532 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
533 }
44f8f95c 534 }
44f8f95c 535 }
536 }
44f8f95c 537 }
538
6a488035 539}