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