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