Don't pass around paymentTableId
[civicrm-core.git] / CRM / Export / BAO / Export.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * This class contains the functions for Component export
36 *
37 */
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
41 // CRM-7675
42 const EXPORT_ROW_COUNT = 100000;
43
44 /**
45 * Get Export component
46 *
47 * @param int $exportMode
48 * Export mode.
49 *
50 * @return string
51 * CiviCRM Export Component
52 */
53 public static function exportComponent($exportMode) {
54 switch ($exportMode) {
55 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
56 $component = 'civicrm_contribution';
57 break;
58
59 case CRM_Export_Form_Select::EVENT_EXPORT:
60 $component = 'civicrm_participant';
61 break;
62
63 case CRM_Export_Form_Select::MEMBER_EXPORT:
64 $component = 'civicrm_membership';
65 break;
66
67 case CRM_Export_Form_Select::PLEDGE_EXPORT:
68 $component = 'civicrm_pledge';
69 break;
70
71 case CRM_Export_Form_Select::GRANT_EXPORT:
72 $component = 'civicrm_grant';
73 break;
74 }
75 return $component;
76 }
77
78 /**
79 * Get Query Group By Clause
80 * @param \CRM_Export_BAO_ExportProcessor $processor
81 * Export Mode
82 * @param object $query
83 * CRM_Contact_BAO_Query
84 *
85 * @return string
86 * Group By Clause
87 */
88 public static function getGroupBy($processor, $query) {
89 $groupBy = NULL;
90 $returnProperties = $processor->getReturnProperties();
91 $exportMode = $processor->getExportMode();
92 $queryMode = $processor->getQueryMode();
93 if (!empty($returnProperties['tags']) || !empty($returnProperties['groups']) ||
94 CRM_Utils_Array::value('notes', $returnProperties) ||
95 // CRM-9552
96 ($queryMode & CRM_Contact_BAO_Query::MODE_CONTACTS && $query->_useGroupBy)
97 ) {
98 $groupBy = "contact_a.id";
99 }
100
101 switch ($exportMode) {
102 case CRM_Export_Form_Select::CONTRIBUTE_EXPORT:
103 $groupBy = 'civicrm_contribution.id';
104 if (CRM_Contribute_BAO_Query::isSoftCreditOptionEnabled()) {
105 // especial group by when soft credit columns are included
106 $groupBy = ['contribution_search_scredit_combined.id', 'contribution_search_scredit_combined.scredit_id'];
107 }
108 break;
109
110 case CRM_Export_Form_Select::EVENT_EXPORT:
111 $groupBy = 'civicrm_participant.id';
112 break;
113
114 case CRM_Export_Form_Select::MEMBER_EXPORT:
115 $groupBy = "civicrm_membership.id";
116 break;
117 }
118
119 if ($queryMode & CRM_Contact_BAO_Query::MODE_ACTIVITY) {
120 $groupBy = "civicrm_activity.id ";
121 }
122
123 return $groupBy ? ' GROUP BY ' . implode(', ', (array) $groupBy) : '';
124 }
125
126 /**
127 * Get the list the export fields.
128 *
129 * @param int $selectAll
130 * User preference while export.
131 * @param array $ids
132 * Contact ids.
133 * @param array $params
134 * Associated array of fields.
135 * @param string $order
136 * Order by clause.
137 * @param array $fields
138 * Associated array of fields.
139 * @param array $moreReturnProperties
140 * Additional return fields.
141 * @param int $exportMode
142 * Export mode.
143 * @param string $componentClause
144 * Component clause.
145 * @param string $componentTable
146 * Component table.
147 * @param bool $mergeSameAddress
148 * Merge records if they have same address.
149 * @param bool $mergeSameHousehold
150 * Merge records if they belong to the same household.
151 *
152 * @param array $exportParams
153 * @param string $queryOperator
154 *
155 * @return array|null
156 * An array can be requested from within a unit test.
157 *
158 * @throws \CRM_Core_Exception
159 */
160 public static function exportComponents(
161 $selectAll,
162 $ids,
163 $params,
164 $order = NULL,
165 $fields = NULL,
166 $moreReturnProperties = NULL,
167 $exportMode = CRM_Export_Form_Select::CONTACT_EXPORT,
168 $componentClause = NULL,
169 $componentTable = NULL,
170 $mergeSameAddress = FALSE,
171 $mergeSameHousehold = FALSE,
172 $exportParams = [],
173 $queryOperator = 'AND'
174 ) {
175
176 $isPostalOnly = (
177 isset($exportParams['postal_mailing_export']['postal_mailing_export']) &&
178 $exportParams['postal_mailing_export']['postal_mailing_export'] == 1
179 );
180
181 if (!$selectAll && $componentTable && !empty($exportParams['additional_group'])) {
182 // If an Additional Group is selected, then all contacts in that group are
183 // added to the export set (filtering out duplicates).
184 // Really - the calling function could do this ... just saying
185 // @todo take a whip to the calling function.
186 CRM_Core_DAO::executeQuery("
187 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"
188 );
189 }
190 // rectify params to what proximity search expects if there is a value for prox_distance
191 // CRM-7021
192 // @todo - move this back to the calling functions
193 if (!empty($params)) {
194 CRM_Contact_BAO_ProximityQuery::fixInputParams($params);
195 }
196 // @todo everything from this line up should go back to the calling functions.
197 $processor = new CRM_Export_BAO_ExportProcessor($exportMode, $fields, $queryOperator, $mergeSameHousehold, $isPostalOnly, $mergeSameAddress);
198 if ($moreReturnProperties) {
199 $processor->setAdditionalRequestedReturnProperties($moreReturnProperties);
200 }
201
202 list($query, $select, $from, $where, $having) = $processor->runQuery($params, $order);
203
204 // This perhaps only needs calling when $mergeSameHousehold == 1
205 self::buildRelatedContactArray($selectAll, $ids, $processor, $componentTable);
206
207 $whereClauses = ['trash_clause' => "contact_a.is_deleted != 1"];
208 if (!$selectAll && $componentTable) {
209 $from .= " INNER JOIN $componentTable ctTable ON ctTable.contact_id = contact_a.id ";
210 }
211 elseif ($componentClause) {
212 $whereClauses[] = $componentClause;
213 }
214
215 // CRM-13982 - check if is deleted
216 foreach ($params as $value) {
217 if ($value[0] == 'contact_is_deleted') {
218 unset($whereClauses['trash_clause']);
219 }
220 }
221
222 if (empty($where)) {
223 $where = "WHERE " . implode(' AND ', $whereClauses);
224 }
225 else {
226 $where .= " AND " . implode(' AND ', $whereClauses);
227 }
228
229 $queryString = "$select $from $where $having";
230
231 $groupBy = self::getGroupBy($processor, $query);
232
233 $queryString .= $groupBy;
234
235 if ($order) {
236 // always add contact_a.id to the ORDER clause
237 // so the order is deterministic
238 //CRM-15301
239 if (strpos('contact_a.id', $order) === FALSE) {
240 $order .= ", contact_a.id";
241 }
242
243 list($field, $dir) = explode(' ', $order, 2);
244 $field = trim($field);
245 if (!empty($processor->getReturnProperties()[$field])) {
246 //CRM-15301
247 $queryString .= " ORDER BY $order";
248 }
249 }
250
251 $addPaymentHeader = FALSE;
252
253 list($outputColumns, $metadata) = self::getExportStructureArrays($processor);
254
255 if ($processor->isMergeSameAddress()) {
256 //make sure the addressee fields are selected
257 //while using merge same address feature
258 // some columns are required for assistance incase they are not already present
259 $exportParams['merge_same_address']['temp_columns'] = $processor->getAdditionalFieldsForSameAddressMerge();
260 // This is silly - we should do this at the point when the array is used...
261 if (isset($exportParams['merge_same_address']['temp_columns']['id'])) {
262 unset($exportParams['merge_same_address']['temp_columns']['id']);
263 $exportParams['merge_same_address']['temp_columns']['civicrm_primary_id'] = 1;
264 }
265 // @todo - this is a temp fix - ideally later we don't set stuff only to unset it.
266 // test exists covering this...
267 foreach (array_keys($exportParams['merge_same_address']['temp_columns']) as $field) {
268 $processor->setColumnAsCalculationOnly($field);
269 }
270 }
271
272 $paymentDetails = [];
273 if ($processor->isExportPaymentFields()) {
274 // get payment related in for event and members
275 $paymentDetails = CRM_Contribute_BAO_Contribution::getContributionDetails($exportMode, $ids);
276 //get all payment headers.
277 // If we haven't selected specific payment fields, load in all the
278 // payment headers.
279 if (!$processor->isExportSpecifiedPaymentFields()) {
280 if (!empty($paymentDetails)) {
281 $addPaymentHeader = TRUE;
282 foreach (array_keys($processor->getPaymentHeaders()) as $paymentField) {
283 $processor->addOutputSpecification($paymentField);
284 }
285 }
286 }
287 }
288
289 $componentDetails = [];
290
291 $rowCount = self::EXPORT_ROW_COUNT;
292 $offset = 0;
293 // we write to temp table often to avoid using too much memory
294 $tempRowCount = 100;
295
296 $count = -1;
297
298 $headerRows = $processor->getHeaderRows();
299 $sqlColumns = $processor->getSQLColumns();
300 $processor->setTemporaryTable(self::createTempTable($sqlColumns));
301 $limitReached = FALSE;
302
303 while (!$limitReached) {
304 $limitQuery = "{$queryString} LIMIT {$offset}, {$rowCount}";
305 CRM_Core_DAO::disableFullGroupByMode();
306 $iterationDAO = CRM_Core_DAO::executeQuery($limitQuery);
307 CRM_Core_DAO::reenableFullGroupByMode();
308 // If this is less than our limit by the end of the iteration we do not need to run the query again to
309 // check if some remain.
310 $rowsThisIteration = 0;
311
312 while ($iterationDAO->fetch()) {
313 $count++;
314 $rowsThisIteration++;
315 $row = $processor->buildRow($query, $iterationDAO, $outputColumns, $metadata, $paymentDetails, $addPaymentHeader, $processor);
316 if ($row === FALSE) {
317 continue;
318 }
319
320 // add component info
321 // write the row to a file
322 $componentDetails[] = $row;
323
324 // output every $tempRowCount rows
325 if ($count % $tempRowCount == 0) {
326 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
327 $componentDetails = [];
328 }
329 }
330 if ($rowsThisIteration < self::EXPORT_ROW_COUNT) {
331 $limitReached = TRUE;
332 }
333 $offset += $rowCount;
334 }
335
336 if ($processor->getTemporaryTable()) {
337 self::writeDetailsToTable($processor, $componentDetails, $sqlColumns);
338
339 // do merge same address and merge same household processing
340 if ($mergeSameAddress) {
341 self::mergeSameAddress($processor, $sqlColumns, $exportParams);
342 }
343
344 // call export hook
345 $table = $processor->getTemporaryTable();
346 CRM_Utils_Hook::export($table, $headerRows, $sqlColumns, $exportMode, $componentTable, $ids);
347 if ($table !== $processor->getTemporaryTable()) {
348 CRM_Core_Error::deprecatedFunctionWarning('altering the export table in the hook is deprecated (in some flows the table itself will be)');
349 $processor->setTemporaryTable($table);
350 }
351
352 // In order to be able to write a unit test against this function we need to suppress
353 // the csv writing. In future hopefully the csv writing & the main processing will be in separate functions.
354 if (empty($exportParams['suppress_csv_for_testing'])) {
355 self::writeCSVFromTable($headerRows, $sqlColumns, $processor);
356 }
357 else {
358 // return tableName sqlColumns headerRows in test context
359 return [$processor->getTemporaryTable(), $sqlColumns, $headerRows, $processor];
360 }
361
362 // delete the export temp table and component table
363 $sql = "DROP TABLE IF EXISTS " . $processor->getTemporaryTable();
364 CRM_Core_DAO::executeQuery($sql);
365 CRM_Core_DAO::reenableFullGroupByMode();
366 CRM_Utils_System::civiExit(0, ['processor' => $processor]);
367 }
368 else {
369 CRM_Core_DAO::reenableFullGroupByMode();
370 throw new CRM_Core_Exception(ts('No records to export'));
371 }
372 }
373
374 /**
375 * Handle import error file creation.
376 */
377 public static function invoke() {
378 $type = CRM_Utils_Request::retrieve('type', 'Positive');
379 $parserName = CRM_Utils_Request::retrieve('parser', 'String');
380 if (empty($parserName) || empty($type)) {
381 return;
382 }
383
384 // clean and ensure parserName is a valid string
385 $parserName = CRM_Utils_String::munge($parserName);
386 $parserClass = explode('_', $parserName);
387
388 // make sure parserClass is in the CRM namespace and
389 // at least 3 levels deep
390 if ($parserClass[0] == 'CRM' &&
391 count($parserClass) >= 3
392 ) {
393 require_once str_replace('_', DIRECTORY_SEPARATOR, $parserName) . ".php";
394 // ensure the functions exists
395 if (method_exists($parserName, 'errorFileName') &&
396 method_exists($parserName, 'saveFileName')
397 ) {
398 $errorFileName = $parserName::errorFileName($type);
399 $saveFileName = $parserName::saveFileName($type);
400 if (!empty($errorFileName) && !empty($saveFileName)) {
401 CRM_Utils_System::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
402 CRM_Utils_System::setHttpHeader('Content-Description', 'File Transfer');
403 CRM_Utils_System::setHttpHeader('Content-Type', 'text/csv');
404 CRM_Utils_System::setHttpHeader('Content-Length', filesize($errorFileName));
405 CRM_Utils_System::setHttpHeader('Content-Disposition', 'attachment; filename=' . $saveFileName);
406
407 readfile($errorFileName);
408 }
409 }
410 }
411 CRM_Utils_System::civiExit();
412 }
413
414 /**
415 * @param $customSearchClass
416 * @param $formValues
417 * @param $order
418 */
419 public static function exportCustom($customSearchClass, $formValues, $order) {
420 $ext = CRM_Extension_System::singleton()->getMapper();
421 if (!$ext->isExtensionClass($customSearchClass)) {
422 require_once str_replace('_', DIRECTORY_SEPARATOR, $customSearchClass) . '.php';
423 }
424 else {
425 require_once $ext->classToPath($customSearchClass);
426 }
427 $search = new $customSearchClass($formValues);
428
429 $includeContactIDs = FALSE;
430 if ($formValues['radio_ts'] == 'ts_sel') {
431 $includeContactIDs = TRUE;
432 }
433
434 $sql = $search->all(0, 0, $order, $includeContactIDs);
435
436 $columns = $search->columns();
437
438 $header = array_keys($columns);
439 $fields = array_values($columns);
440
441 $rows = [];
442 $dao = CRM_Core_DAO::executeQuery($sql);
443 $alterRow = FALSE;
444 if (method_exists($search, 'alterRow')) {
445 $alterRow = TRUE;
446 }
447 while ($dao->fetch()) {
448 $row = [];
449
450 foreach ($fields as $field) {
451 $unqualified_field = CRM_Utils_Array::First(array_slice(explode('.', $field), -1));
452 $row[$field] = $dao->$unqualified_field;
453 }
454 if ($alterRow) {
455 $search->alterRow($row);
456 }
457 $rows[] = $row;
458 }
459
460 CRM_Core_Report_Excel::writeCSVFile(ts('CiviCRM Contact Search'), $header, $rows);
461 CRM_Utils_System::civiExit();
462 }
463
464 /**
465 * @param \CRM_Export_BAO_ExportProcessor $processor
466 * @param $details
467 * @param $sqlColumns
468 */
469 public static function writeDetailsToTable($processor, $details, $sqlColumns) {
470 $tableName = $processor->getTemporaryTable();
471 if (empty($details)) {
472 return;
473 }
474
475 $sql = "
476 SELECT max(id)
477 FROM $tableName
478 ";
479
480 $id = CRM_Core_DAO::singleValueQuery($sql);
481 if (!$id) {
482 $id = 0;
483 }
484
485 $sqlClause = [];
486
487 foreach ($details as $row) {
488 $id++;
489 $valueString = [$id];
490 foreach ($row as $value) {
491 if (empty($value)) {
492 $valueString[] = "''";
493 }
494 else {
495 $valueString[] = "'" . CRM_Core_DAO::escapeString($value) . "'";
496 }
497 }
498 $sqlClause[] = '(' . implode(',', $valueString) . ')';
499 }
500 $sqlColumns = array_merge(['id' => 1], $sqlColumns);
501 $sqlColumnString = '(' . implode(',', array_keys($sqlColumns)) . ')';
502
503 $sqlValueString = implode(",\n", $sqlClause);
504
505 $sql = "
506 INSERT INTO $tableName $sqlColumnString
507 VALUES $sqlValueString
508 ";
509 CRM_Core_DAO::executeQuery($sql);
510 }
511
512 /**
513 * @param $sqlColumns
514 *
515 * @return string
516 */
517 public static function createTempTable($sqlColumns) {
518 //creating a temporary table for the search result that need be exported
519 $exportTempTable = CRM_Utils_SQL_TempTable::build()->setDurable()->setCategory('export');
520
521 // also create the sql table
522 $exportTempTable->drop();
523
524 $sql = " id int unsigned NOT NULL AUTO_INCREMENT, ";
525 if (!empty($sqlColumns)) {
526 $sql .= implode(",\n", array_values($sqlColumns)) . ',';
527 }
528
529 $sql .= "\n PRIMARY KEY ( id )";
530
531 // add indexes for street_address and household_name if present
532 $addIndices = [
533 'street_address',
534 'household_name',
535 'civicrm_primary_id',
536 ];
537
538 foreach ($addIndices as $index) {
539 if (isset($sqlColumns[$index])) {
540 $sql .= ",
541 INDEX index_{$index}( $index )
542 ";
543 }
544 }
545
546 $exportTempTable->createWithColumns($sql);
547 return $exportTempTable->getName();
548 }
549
550 /**
551 * @param \CRM_Export_BAO_ExportProcessor $processor
552 * @param $sqlColumns
553 * @param array $exportParams
554 */
555 public static function mergeSameAddress($processor, &$sqlColumns, $exportParams) {
556 $greetingOptions = CRM_Export_Form_Select::getGreetingOptions();
557
558 if (!empty($greetingOptions)) {
559 // Greeting options is keyed by 'postal_greeting' or 'addressee'.
560 foreach ($greetingOptions as $key => $value) {
561 if ($option = CRM_Utils_Array::value($key, $exportParams)) {
562 if ($greetingOptions[$key][$option] == ts('Other')) {
563 $exportParams[$key] = $exportParams["{$key}_other"];
564 }
565 elseif ($greetingOptions[$key][$option] == ts('List of names')) {
566 $exportParams[$key] = '';
567 }
568 else {
569 $exportParams[$key] = $greetingOptions[$key][$option];
570 }
571 }
572 }
573 }
574 $tableName = $processor->getTemporaryTable();
575 // check if any records are present based on if they have used shared address feature,
576 // and not based on if city / state .. matches.
577 $sql = "
578 SELECT r1.id as copy_id,
579 r1.civicrm_primary_id as copy_contact_id,
580 r1.addressee as copy_addressee,
581 r1.addressee_id as copy_addressee_id,
582 r1.postal_greeting as copy_postal_greeting,
583 r1.postal_greeting_id as copy_postal_greeting_id,
584 r2.id as master_id,
585 r2.civicrm_primary_id as master_contact_id,
586 r2.postal_greeting as master_postal_greeting,
587 r2.postal_greeting_id as master_postal_greeting_id,
588 r2.addressee as master_addressee,
589 r2.addressee_id as master_addressee_id
590 FROM $tableName r1
591 INNER JOIN civicrm_address adr ON r1.master_id = adr.id
592 INNER JOIN $tableName r2 ON adr.contact_id = r2.civicrm_primary_id
593 ORDER BY r1.id";
594 $linkedMerge = $processor->buildMasterCopyArray($sql, $exportParams, TRUE);
595
596 // find all the records that have the same street address BUT not in a household
597 // require match on city and state as well
598 $sql = "
599 SELECT r1.id as master_id,
600 r1.civicrm_primary_id as master_contact_id,
601 r1.postal_greeting as master_postal_greeting,
602 r1.postal_greeting_id as master_postal_greeting_id,
603 r1.addressee as master_addressee,
604 r1.addressee_id as master_addressee_id,
605 r2.id as copy_id,
606 r2.civicrm_primary_id as copy_contact_id,
607 r2.postal_greeting as copy_postal_greeting,
608 r2.postal_greeting_id as copy_postal_greeting_id,
609 r2.addressee as copy_addressee,
610 r2.addressee_id as copy_addressee_id
611 FROM $tableName r1
612 LEFT JOIN $tableName r2 ON ( r1.street_address = r2.street_address AND
613 r1.city = r2.city AND
614 r1.state_province_id = r2.state_province_id )
615 WHERE ( r1.household_name IS NULL OR r1.household_name = '' )
616 AND ( r2.household_name IS NULL OR r2.household_name = '' )
617 AND ( r1.street_address != '' )
618 AND r2.id > r1.id
619 ORDER BY r1.id
620 ";
621 $merge = $processor->buildMasterCopyArray($sql, $exportParams);
622
623 // unset ids from $merge already present in $linkedMerge
624 foreach ($linkedMerge as $masterID => $values) {
625 $keys = [$masterID];
626 $keys = array_merge($keys, array_keys($values['copy']));
627 foreach ($merge as $mid => $vals) {
628 if (in_array($mid, $keys)) {
629 unset($merge[$mid]);
630 }
631 else {
632 foreach ($values['copy'] as $copyId) {
633 if (in_array($copyId, $keys)) {
634 unset($merge[$mid]['copy'][$copyId]);
635 }
636 }
637 }
638 }
639 }
640 $merge = $merge + $linkedMerge;
641
642 foreach ($merge as $masterID => $values) {
643 $sql = "
644 UPDATE $tableName
645 SET addressee = %1, postal_greeting = %2, email_greeting = %3
646 WHERE id = %4
647 ";
648 $params = [
649 1 => [$values['addressee'], 'String'],
650 2 => [$values['postalGreeting'], 'String'],
651 3 => [$values['emailGreeting'], 'String'],
652 4 => [$masterID, 'Integer'],
653 ];
654 CRM_Core_DAO::executeQuery($sql, $params);
655
656 // delete all copies
657 $deleteIDs = array_keys($values['copy']);
658 $deleteIDString = implode(',', $deleteIDs);
659 $sql = "
660 DELETE FROM $tableName
661 WHERE id IN ( $deleteIDString )
662 ";
663 CRM_Core_DAO::executeQuery($sql);
664 }
665
666 // unset temporary columns that were added for postal mailing format
667 // @todo - this part is pretty close to ready to be removed....
668 if (!empty($exportParams['merge_same_address']['temp_columns'])) {
669 $unsetKeys = array_keys($sqlColumns);
670 foreach ($unsetKeys as $headerKey => $sqlColKey) {
671 if (array_key_exists($sqlColKey, $exportParams['merge_same_address']['temp_columns'])) {
672 unset($sqlColumns[$sqlColKey]);
673 }
674 }
675 }
676 }
677
678 /**
679 * @param $headerRows
680 * @param $sqlColumns
681 * @param \CRM_Export_BAO_ExportProcessor $processor
682 */
683 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
684 $exportTempTable = $processor->getTemporaryTable();
685 $exportMode = $processor->getExportMode();
686 $writeHeader = TRUE;
687 $offset = 0;
688 $limit = self::EXPORT_ROW_COUNT;
689
690 $query = "SELECT * FROM $exportTempTable";
691
692 while (1) {
693 $limitQuery = $query . "
694 LIMIT $offset, $limit
695 ";
696 $dao = CRM_Core_DAO::executeQuery($limitQuery);
697
698 if ($dao->N <= 0) {
699 break;
700 }
701
702 $componentDetails = [];
703 while ($dao->fetch()) {
704 $row = [];
705
706 foreach ($sqlColumns as $column => $dontCare) {
707 $row[$column] = $dao->$column;
708 }
709 $componentDetails[] = $row;
710 }
711 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
712 $headerRows,
713 $componentDetails,
714 NULL,
715 $writeHeader
716 );
717
718 $writeHeader = FALSE;
719 $offset += $limit;
720 }
721 }
722
723 /**
724 * Build componentPayment fields.
725 *
726 * This is no longer used by export but BAO_Mapping still calls it & we
727 * should find a generic way to handle this or move this to that class.
728 *
729 * @deprecated
730 */
731 public static function componentPaymentFields() {
732 static $componentPaymentFields;
733 if (!isset($componentPaymentFields)) {
734 $componentPaymentFields = [
735 'componentPaymentField_total_amount' => ts('Total Amount'),
736 'componentPaymentField_contribution_status' => ts('Contribution Status'),
737 'componentPaymentField_received_date' => ts('Date Received'),
738 'componentPaymentField_payment_instrument' => ts('Payment Method'),
739 'componentPaymentField_transaction_id' => ts('Transaction ID'),
740 ];
741 }
742 return $componentPaymentFields;
743 }
744
745 /**
746 * Get the various arrays that we use to structure our output.
747 *
748 * The extraction of these has been moved to a separate function for clarity and so that
749 * tests can be added - in particular on the $outputHeaders array.
750 *
751 * However it still feels a bit like something that I'm too polite to write down and this should be seen
752 * as a step on the refactoring path rather than how it should be.
753 *
754 * @param \CRM_Export_BAO_ExportProcessor $processor
755 *
756 * @return array
757 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
758 * alias for the field generated by BAO_Query object.
759 * - headerRows Array of the column header strings to put in the csv header - non-associative.
760 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
761 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
762 * I'm too embarassed to discuss here.
763 * The keys need
764 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
765 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
766 * in the main DAO loop is done once per row & that coule be 100,000 times.)
767 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
768 * - a) the function used is more efficient or
769 * - b) this code is old & outdated. Submit your answers to circular bin or better
770 * yet find a way to comment them for posterity.
771 */
772 public static function getExportStructureArrays($processor) {
773 $outputColumns = $metadata = [];
774 $queryFields = $processor->getQueryFields();
775 foreach ($processor->getReturnProperties() as $key => $value) {
776 if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
777 $outputColumns[$key] = $value;
778 $processor->addOutputSpecification($key);
779 }
780 elseif ($processor->isRelationshipTypeKey($key)) {
781 $outputColumns[$key] = $value;
782 foreach ($value as $relationField => $relationValue) {
783 // below block is same as primary block (duplicate)
784 if (isset($queryFields[$relationField]['title'])) {
785 $processor->addOutputSpecification($relationField, $key);
786 }
787 elseif (is_array($relationValue) && $relationField == 'location') {
788 // fix header for location type case
789 foreach ($relationValue as $ltype => $val) {
790 foreach (array_keys($val) as $fld) {
791 $type = explode('-', $fld);
792 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
793 }
794 }
795 }
796 }
797 }
798 else {
799 foreach ($value as $locationType => $locationFields) {
800 foreach (array_keys($locationFields) as $locationFieldName) {
801 $type = explode('-', $locationFieldName);
802
803 $actualDBFieldName = $type[0];
804 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
805
806 if (!empty($type[1])) {
807 $daoFieldName .= "-" . $type[1];
808 }
809 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
810 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
811 $outputColumns[$daoFieldName] = TRUE;
812 }
813 }
814 }
815 }
816 return [$outputColumns, $metadata];
817 }
818
819 /**
820 * Get the values of linked household contact.
821 *
822 * @param CRM_Core_DAO $relDAO
823 * @param array $value
824 * @param string $field
825 * @param array $row
826 */
827 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
828 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
829 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
830 $i18n = CRM_Core_I18n::singleton();
831 $field = $field . '_';
832
833 foreach ($value as $relationField => $relationValue) {
834 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
835 $fieldValue = $relDAO->$relationField;
836 if ($relationField == 'phone_type_id') {
837 $fieldValue = $phoneTypes[$relationValue];
838 }
839 elseif ($relationField == 'provider_id') {
840 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
841 }
842 // CRM-13995
843 elseif (is_object($relDAO) && in_array($relationField, [
844 'email_greeting',
845 'postal_greeting',
846 'addressee',
847 ])) {
848 //special case for greeting replacement
849 $fldValue = "{$relationField}_display";
850 $fieldValue = $relDAO->$fldValue;
851 }
852 }
853 elseif (is_object($relDAO) && $relationField == 'state_province') {
854 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
855 }
856 elseif (is_object($relDAO) && $relationField == 'country') {
857 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
858 }
859 else {
860 $fieldValue = '';
861 }
862 $relPrefix = $field . $relationField;
863
864 if (is_object($relDAO) && $relationField == 'id') {
865 $row[$relPrefix] = $relDAO->contact_id;
866 }
867 elseif (is_array($relationValue) && $relationField == 'location') {
868 foreach ($relationValue as $ltype => $val) {
869 // If the location name has a space in it the we need to handle that. This
870 // is kinda hacky but specifically covered in the ExportTest so later efforts to
871 // improve it should be secure in the knowled it will be caught.
872 $ltype = str_replace(' ', '_', $ltype);
873 foreach (array_keys($val) as $fld) {
874 $type = explode('-', $fld);
875 $fldValue = "{$ltype}-" . $type[0];
876 if (!empty($type[1])) {
877 $fldValue .= "-" . $type[1];
878 }
879 // CRM-3157: localise country, region (both have ‘country’ context)
880 // and state_province (‘province’ context)
881 switch (TRUE) {
882 case (!is_object($relDAO)):
883 $row[$field . '_' . $fldValue] = '';
884 break;
885
886 case in_array('country', $type):
887 case in_array('world_region', $type):
888 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
889 ['context' => 'country']
890 );
891 break;
892
893 case in_array('state_province', $type):
894 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
895 ['context' => 'province']
896 );
897 break;
898
899 default:
900 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
901 break;
902 }
903 }
904 }
905 }
906 elseif (isset($fieldValue) && $fieldValue != '') {
907 //check for custom data
908 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
909 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
910 }
911 else {
912 //normal relationship fields
913 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
914 switch ($relationField) {
915 case 'country':
916 case 'world_region':
917 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
918 break;
919
920 case 'state_province':
921 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
922 break;
923
924 default:
925 $row[$relPrefix] = $fieldValue;
926 break;
927 }
928 }
929 }
930 else {
931 // if relation field is empty or null
932 $row[$relPrefix] = '';
933 }
934 }
935 }
936
937 /**
938 * Get the ids that we want to get related contact details for.
939 *
940 * @param array $ids
941 * @param int $exportMode
942 *
943 * @return array
944 */
945 protected static function getIDsForRelatedContact($ids, $exportMode) {
946 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
947 return $ids;
948 }
949 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
950 $relIDs = [];
951 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
952 $dao = CRM_Core_DAO::executeQuery("
953 SELECT contact_id FROM civicrm_activity_contact
954 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
955 record_type_id = {$sourceID}
956 ");
957
958 while ($dao->fetch()) {
959 $relIDs[] = $dao->contact_id;
960 }
961 return $relIDs;
962 }
963 $component = self::exportComponent($exportMode);
964
965 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
966 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
967 }
968 else {
969 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
970 }
971 }
972
973 /**
974 * @param $selectAll
975 * @param $ids
976 * @param \CRM_Export_BAO_ExportProcessor $processor
977 * @param $componentTable
978 */
979 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
980 $allRelContactArray = $relationQuery = [];
981 $queryMode = $processor->getQueryMode();
982 $exportMode = $processor->getExportMode();
983
984 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
985 $allRelContactArray[$relationshipKey] = [];
986 // build Query for each relationship
987 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
988 NULL, FALSE, FALSE, $queryMode
989 );
990 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
991
992 list($id, $direction) = explode('_', $relationshipKey, 2);
993 // identify the relationship direction
994 $contactA = 'contact_id_a';
995 $contactB = 'contact_id_b';
996 if ($direction == 'b_a') {
997 $contactA = 'contact_id_b';
998 $contactB = 'contact_id_a';
999 }
1000 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
1001
1002 $relationshipJoin = $relationshipClause = '';
1003 if (!$selectAll && $componentTable) {
1004 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1005 }
1006 elseif (!empty($relIDs)) {
1007 $relID = implode(',', $relIDs);
1008 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1009 }
1010
1011 $relationFrom = " {$relationFrom}
1012 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1013 {$relationshipJoin} ";
1014
1015 //check for active relationship status only
1016 $today = date('Ymd');
1017 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1018 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1019 CRM_Core_DAO::disableFullGroupByMode();
1020 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1021 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1022
1023 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
1024 CRM_Core_DAO::reenableFullGroupByMode();
1025
1026 while ($allRelContactDAO->fetch()) {
1027 $relationQuery->convertToPseudoNames($allRelContactDAO);
1028 $row = [];
1029 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1030 self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1031 foreach (array_keys($relationReturnProperties) as $property) {
1032 if ($property === 'location') {
1033 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1034 // $processor->setRelationshipValue from fetchRelationshipDetails
1035 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1036 foreach (array_keys($locationValues) as $locationValue) {
1037 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1038 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
1039 }
1040 }
1041 }
1042 else {
1043 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
1044 }
1045 }
1046 }
1047 }
1048 }
1049
1050 }