Minor code relocation
[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 int $contactId
695 * @param array $exportParams
696 *
697 * @return array
698 */
699 public static function _replaceMergeTokens($contactId, $exportParams) {
700 $greetings = [];
701 $contact = NULL;
702
703 $greetingFields = [
704 'postal_greeting',
705 'addressee',
706 ];
707 foreach ($greetingFields as $greeting) {
708 if (!empty($exportParams[$greeting])) {
709 $greetingLabel = $exportParams[$greeting];
710 if (empty($contact)) {
711 $values = [
712 'id' => $contactId,
713 'version' => 3,
714 ];
715 $contact = civicrm_api('contact', 'get', $values);
716
717 if (!empty($contact['is_error'])) {
718 return $greetings;
719 }
720 $contact = $contact['values'][$contact['id']];
721 }
722
723 $tokens = ['contact' => $greetingLabel];
724 $greetings[$greeting] = CRM_Utils_Token::replaceContactTokens($greetingLabel, $contact, NULL, $tokens);
725 }
726 }
727 return $greetings;
728 }
729
730 /**
731 * @param \CRM_Export_BAO_ExportProcessor $processor
732 * @param $sql
733 * @param array $exportParams
734 * @param bool $sharedAddress
735 *
736 * @return array
737 */
738 public static function _buildMasterCopyArray($processor, $sql, $exportParams, $sharedAddress = FALSE) {
739 static $contactGreetingTokens = [];
740
741 $addresseeOptions = CRM_Core_OptionGroup::values('addressee');
742 $postalOptions = CRM_Core_OptionGroup::values('postal_greeting');
743
744 $merge = $parents = [];
745 $dao = CRM_Core_DAO::executeQuery($sql);
746
747 while ($dao->fetch()) {
748 $masterID = $dao->master_id;
749 $copyID = $dao->copy_id;
750 $masterPostalGreeting = $dao->master_postal_greeting;
751 $masterAddressee = $dao->master_addressee;
752 $copyAddressee = $dao->copy_addressee;
753
754 if (!$sharedAddress) {
755 if (!isset($contactGreetingTokens[$dao->master_contact_id])) {
756 $contactGreetingTokens[$dao->master_contact_id] = self::_replaceMergeTokens($dao->master_contact_id, $exportParams);
757 }
758 $masterPostalGreeting = CRM_Utils_Array::value('postal_greeting',
759 $contactGreetingTokens[$dao->master_contact_id], $dao->master_postal_greeting
760 );
761 $masterAddressee = CRM_Utils_Array::value('addressee',
762 $contactGreetingTokens[$dao->master_contact_id], $dao->master_addressee
763 );
764
765 if (!isset($contactGreetingTokens[$dao->copy_contact_id])) {
766 $contactGreetingTokens[$dao->copy_contact_id] = self::_replaceMergeTokens($dao->copy_contact_id, $exportParams);
767 }
768 $copyPostalGreeting = CRM_Utils_Array::value('postal_greeting',
769 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_postal_greeting
770 );
771 $copyAddressee = CRM_Utils_Array::value('addressee',
772 $contactGreetingTokens[$dao->copy_contact_id], $dao->copy_addressee
773 );
774 }
775
776 if (!isset($merge[$masterID])) {
777 // check if this is an intermediate child
778 // this happens if there are 3 or more matches a,b, c
779 // the above query will return a, b / a, c / b, c
780 // we might be doing a bit more work, but for now its ok, unless someone
781 // knows how to fix the query above
782 if (isset($parents[$masterID])) {
783 $masterID = $parents[$masterID];
784 }
785 else {
786 $merge[$masterID] = [
787 'addressee' => $masterAddressee,
788 'copy' => [],
789 'postalGreeting' => $masterPostalGreeting,
790 ];
791 $merge[$masterID]['emailGreeting'] = &$merge[$masterID]['postalGreeting'];
792 }
793 }
794 $parents[$copyID] = $masterID;
795
796 if (!$sharedAddress && !array_key_exists($copyID, $merge[$masterID]['copy'])) {
797
798 if (!empty($exportParams['postal_greeting_other']) &&
799 count($merge[$masterID]['copy']) >= 1
800 ) {
801 // use static greetings specified if no of contacts > 2
802 $merge[$masterID]['postalGreeting'] = $exportParams['postal_greeting_other'];
803 }
804 elseif ($copyPostalGreeting) {
805 $processor->trimNonTokensFromAddressString($copyPostalGreeting,
806 $postalOptions[$dao->copy_postal_greeting_id],
807 $exportParams
808 );
809 $merge[$masterID]['postalGreeting'] = "{$merge[$masterID]['postalGreeting']}, {$copyPostalGreeting}";
810 // if there happens to be a duplicate, remove it
811 $merge[$masterID]['postalGreeting'] = str_replace(" {$copyPostalGreeting},", "", $merge[$masterID]['postalGreeting']);
812 }
813
814 if (!empty($exportParams['addressee_other']) &&
815 count($merge[$masterID]['copy']) >= 1
816 ) {
817 // use static greetings specified if no of contacts > 2
818 $merge[$masterID]['addressee'] = $exportParams['addressee_other'];
819 }
820 elseif ($copyAddressee) {
821 $processor->trimNonTokensFromAddressString($copyAddressee,
822 $addresseeOptions[$dao->copy_addressee_id],
823 $exportParams, 'addressee'
824 );
825 $merge[$masterID]['addressee'] = "{$merge[$masterID]['addressee']}, " . trim($copyAddressee);
826 }
827 }
828 $merge[$masterID]['copy'][$copyID] = $copyAddressee;
829 }
830
831 return $merge;
832 }
833
834 /**
835 * @param $headerRows
836 * @param $sqlColumns
837 * @param \CRM_Export_BAO_ExportProcessor $processor
838 */
839 public static function writeCSVFromTable($headerRows, $sqlColumns, $processor) {
840 $exportTempTable = $processor->getTemporaryTable();
841 $exportMode = $processor->getExportMode();
842 $writeHeader = TRUE;
843 $offset = 0;
844 $limit = self::EXPORT_ROW_COUNT;
845
846 $query = "SELECT * FROM $exportTempTable";
847
848 while (1) {
849 $limitQuery = $query . "
850 LIMIT $offset, $limit
851 ";
852 $dao = CRM_Core_DAO::executeQuery($limitQuery);
853
854 if ($dao->N <= 0) {
855 break;
856 }
857
858 $componentDetails = [];
859 while ($dao->fetch()) {
860 $row = [];
861
862 foreach ($sqlColumns as $column => $dontCare) {
863 $row[$column] = $dao->$column;
864 }
865 $componentDetails[] = $row;
866 }
867 CRM_Core_Report_Excel::writeCSVFile($processor->getExportFileName(),
868 $headerRows,
869 $componentDetails,
870 NULL,
871 $writeHeader
872 );
873
874 $writeHeader = FALSE;
875 $offset += $limit;
876 }
877 }
878
879 /**
880 * Build componentPayment fields.
881 *
882 * This is no longer used by export but BAO_Mapping still calls it & we
883 * should find a generic way to handle this or move this to that class.
884 *
885 * @deprecated
886 */
887 public static function componentPaymentFields() {
888 static $componentPaymentFields;
889 if (!isset($componentPaymentFields)) {
890 $componentPaymentFields = [
891 'componentPaymentField_total_amount' => ts('Total Amount'),
892 'componentPaymentField_contribution_status' => ts('Contribution Status'),
893 'componentPaymentField_received_date' => ts('Date Received'),
894 'componentPaymentField_payment_instrument' => ts('Payment Method'),
895 'componentPaymentField_transaction_id' => ts('Transaction ID'),
896 ];
897 }
898 return $componentPaymentFields;
899 }
900
901 /**
902 * Get the various arrays that we use to structure our output.
903 *
904 * The extraction of these has been moved to a separate function for clarity and so that
905 * tests can be added - in particular on the $outputHeaders array.
906 *
907 * However it still feels a bit like something that I'm too polite to write down and this should be seen
908 * as a step on the refactoring path rather than how it should be.
909 *
910 * @param \CRM_Export_BAO_ExportProcessor $processor
911 *
912 * @return array
913 * - outputColumns Array of columns to be exported. The values don't matter but the key must match the
914 * alias for the field generated by BAO_Query object.
915 * - headerRows Array of the column header strings to put in the csv header - non-associative.
916 * - sqlColumns Array of column names for the temp table. Not too sure why outputColumns can't be used here.
917 * - metadata Array of fields with specific parameters to pass to the translate function or another hacky nasty solution
918 * I'm too embarassed to discuss here.
919 * The keys need
920 * - to match the outputColumns keys (yes, the fact we ignore the output columns values & then pass another array with values
921 * we could use does suggest further refactors. However, you future improver, do remember that every check you do
922 * in the main DAO loop is done once per row & that coule be 100,000 times.)
923 * Finally a pop quiz: We need the translate context because we use a function other than ts() - is this because
924 * - a) the function used is more efficient or
925 * - b) this code is old & outdated. Submit your answers to circular bin or better
926 * yet find a way to comment them for posterity.
927 */
928 public static function getExportStructureArrays($processor) {
929 $outputColumns = $metadata = [];
930 $queryFields = $processor->getQueryFields();
931 foreach ($processor->getReturnProperties() as $key => $value) {
932 if (($key != 'location' || !is_array($value)) && !$processor->isRelationshipTypeKey($key)) {
933 $outputColumns[$key] = $value;
934 $processor->addOutputSpecification($key);
935 }
936 elseif ($processor->isRelationshipTypeKey($key)) {
937 $outputColumns[$key] = $value;
938 foreach ($value as $relationField => $relationValue) {
939 // below block is same as primary block (duplicate)
940 if (isset($queryFields[$relationField]['title'])) {
941 $processor->addOutputSpecification($relationField, $key);
942 }
943 elseif (is_array($relationValue) && $relationField == 'location') {
944 // fix header for location type case
945 foreach ($relationValue as $ltype => $val) {
946 foreach (array_keys($val) as $fld) {
947 $type = explode('-', $fld);
948 $processor->addOutputSpecification($type[0], $key, $ltype, CRM_Utils_Array::value(1, $type));
949 }
950 }
951 }
952 }
953 }
954 else {
955 foreach ($value as $locationType => $locationFields) {
956 foreach (array_keys($locationFields) as $locationFieldName) {
957 $type = explode('-', $locationFieldName);
958
959 $actualDBFieldName = $type[0];
960 $daoFieldName = CRM_Utils_String::munge($locationType) . '-' . $actualDBFieldName;
961
962 if (!empty($type[1])) {
963 $daoFieldName .= "-" . $type[1];
964 }
965 $processor->addOutputSpecification($actualDBFieldName, NULL, $locationType, CRM_Utils_Array::value(1, $type));
966 $metadata[$daoFieldName] = $processor->getMetaDataForField($actualDBFieldName);
967 $outputColumns[$daoFieldName] = TRUE;
968 }
969 }
970 }
971 }
972 return [$outputColumns, $metadata];
973 }
974
975 /**
976 * Get the values of linked household contact.
977 *
978 * @param CRM_Core_DAO $relDAO
979 * @param array $value
980 * @param string $field
981 * @param array $row
982 */
983 private static function fetchRelationshipDetails($relDAO, $value, $field, &$row) {
984 $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
985 $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
986 $i18n = CRM_Core_I18n::singleton();
987 $field = $field . '_';
988
989 foreach ($value as $relationField => $relationValue) {
990 if (is_object($relDAO) && property_exists($relDAO, $relationField)) {
991 $fieldValue = $relDAO->$relationField;
992 if ($relationField == 'phone_type_id') {
993 $fieldValue = $phoneTypes[$relationValue];
994 }
995 elseif ($relationField == 'provider_id') {
996 $fieldValue = CRM_Utils_Array::value($relationValue, $imProviders);
997 }
998 // CRM-13995
999 elseif (is_object($relDAO) && in_array($relationField, [
1000 'email_greeting',
1001 'postal_greeting',
1002 'addressee',
1003 ])) {
1004 //special case for greeting replacement
1005 $fldValue = "{$relationField}_display";
1006 $fieldValue = $relDAO->$fldValue;
1007 }
1008 }
1009 elseif (is_object($relDAO) && $relationField == 'state_province') {
1010 $fieldValue = CRM_Core_PseudoConstant::stateProvince($relDAO->state_province_id);
1011 }
1012 elseif (is_object($relDAO) && $relationField == 'country') {
1013 $fieldValue = CRM_Core_PseudoConstant::country($relDAO->country_id);
1014 }
1015 else {
1016 $fieldValue = '';
1017 }
1018 $relPrefix = $field . $relationField;
1019
1020 if (is_object($relDAO) && $relationField == 'id') {
1021 $row[$relPrefix] = $relDAO->contact_id;
1022 }
1023 elseif (is_array($relationValue) && $relationField == 'location') {
1024 foreach ($relationValue as $ltype => $val) {
1025 // If the location name has a space in it the we need to handle that. This
1026 // is kinda hacky but specifically covered in the ExportTest so later efforts to
1027 // improve it should be secure in the knowled it will be caught.
1028 $ltype = str_replace(' ', '_', $ltype);
1029 foreach (array_keys($val) as $fld) {
1030 $type = explode('-', $fld);
1031 $fldValue = "{$ltype}-" . $type[0];
1032 if (!empty($type[1])) {
1033 $fldValue .= "-" . $type[1];
1034 }
1035 // CRM-3157: localise country, region (both have ‘country’ context)
1036 // and state_province (‘province’ context)
1037 switch (TRUE) {
1038 case (!is_object($relDAO)):
1039 $row[$field . '_' . $fldValue] = '';
1040 break;
1041
1042 case in_array('country', $type):
1043 case in_array('world_region', $type):
1044 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1045 ['context' => 'country']
1046 );
1047 break;
1048
1049 case in_array('state_province', $type):
1050 $row[$field . '_' . $fldValue] = $i18n->crm_translate($relDAO->$fldValue,
1051 ['context' => 'province']
1052 );
1053 break;
1054
1055 default:
1056 $row[$field . '_' . $fldValue] = $relDAO->$fldValue;
1057 break;
1058 }
1059 }
1060 }
1061 }
1062 elseif (isset($fieldValue) && $fieldValue != '') {
1063 //check for custom data
1064 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($relationField)) {
1065 $row[$relPrefix] = CRM_Core_BAO_CustomField::displayValue($fieldValue, $cfID);
1066 }
1067 else {
1068 //normal relationship fields
1069 // CRM-3157: localise country, region (both have ‘country’ context) and state_province (‘province’ context)
1070 switch ($relationField) {
1071 case 'country':
1072 case 'world_region':
1073 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'country']);
1074 break;
1075
1076 case 'state_province':
1077 $row[$relPrefix] = $i18n->crm_translate($fieldValue, ['context' => 'province']);
1078 break;
1079
1080 default:
1081 $row[$relPrefix] = $fieldValue;
1082 break;
1083 }
1084 }
1085 }
1086 else {
1087 // if relation field is empty or null
1088 $row[$relPrefix] = '';
1089 }
1090 }
1091 }
1092
1093 /**
1094 * Get the ids that we want to get related contact details for.
1095 *
1096 * @param array $ids
1097 * @param int $exportMode
1098 *
1099 * @return array
1100 */
1101 protected static function getIDsForRelatedContact($ids, $exportMode) {
1102 if ($exportMode == CRM_Export_Form_Select::CONTACT_EXPORT) {
1103 return $ids;
1104 }
1105 if ($exportMode == CRM_Export_Form_Select::ACTIVITY_EXPORT) {
1106 $relIDs = [];
1107 $sourceID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_ActivityContact', 'record_type_id', 'Activity Source');
1108 $dao = CRM_Core_DAO::executeQuery("
1109 SELECT contact_id FROM civicrm_activity_contact
1110 WHERE activity_id IN ( " . implode(',', $ids) . ") AND
1111 record_type_id = {$sourceID}
1112 ");
1113
1114 while ($dao->fetch()) {
1115 $relIDs[] = $dao->contact_id;
1116 }
1117 return $relIDs;
1118 }
1119 $component = self::exportComponent($exportMode);
1120
1121 if ($exportMode == CRM_Export_Form_Select::CASE_EXPORT) {
1122 return CRM_Case_BAO_Case::retrieveContactIdsByCaseId($ids);
1123 }
1124 else {
1125 return CRM_Core_DAO::getContactIDsFromComponent($ids, $component);
1126 }
1127 }
1128
1129 /**
1130 * @param $selectAll
1131 * @param $ids
1132 * @param \CRM_Export_BAO_ExportProcessor $processor
1133 * @param $componentTable
1134 */
1135 protected static function buildRelatedContactArray($selectAll, $ids, $processor, $componentTable) {
1136 $allRelContactArray = $relationQuery = [];
1137 $queryMode = $processor->getQueryMode();
1138 $exportMode = $processor->getExportMode();
1139
1140 foreach ($processor->getRelationshipReturnProperties() as $relationshipKey => $relationReturnProperties) {
1141 $allRelContactArray[$relationshipKey] = [];
1142 // build Query for each relationship
1143 $relationQuery = new CRM_Contact_BAO_Query(NULL, $relationReturnProperties,
1144 NULL, FALSE, FALSE, $queryMode
1145 );
1146 list($relationSelect, $relationFrom, $relationWhere, $relationHaving) = $relationQuery->query();
1147
1148 list($id, $direction) = explode('_', $relationshipKey, 2);
1149 // identify the relationship direction
1150 $contactA = 'contact_id_a';
1151 $contactB = 'contact_id_b';
1152 if ($direction == 'b_a') {
1153 $contactA = 'contact_id_b';
1154 $contactB = 'contact_id_a';
1155 }
1156 $relIDs = self::getIDsForRelatedContact($ids, $exportMode);
1157
1158 $relationshipJoin = $relationshipClause = '';
1159 if (!$selectAll && $componentTable) {
1160 $relationshipJoin = " INNER JOIN {$componentTable} ctTable ON ctTable.contact_id = {$contactA}";
1161 }
1162 elseif (!empty($relIDs)) {
1163 $relID = implode(',', $relIDs);
1164 $relationshipClause = " AND crel.{$contactA} IN ( {$relID} )";
1165 }
1166
1167 $relationFrom = " {$relationFrom}
1168 INNER JOIN civicrm_relationship crel ON crel.{$contactB} = contact_a.id AND crel.relationship_type_id = {$id}
1169 {$relationshipJoin} ";
1170
1171 //check for active relationship status only
1172 $today = date('Ymd');
1173 $relationActive = " AND (crel.is_active = 1 AND ( crel.end_date is NULL OR crel.end_date >= {$today} ) )";
1174 $relationWhere = " WHERE contact_a.is_deleted = 0 {$relationshipClause} {$relationActive}";
1175 CRM_Core_DAO::disableFullGroupByMode();
1176 $relationSelect = "{$relationSelect}, {$contactA} as refContact ";
1177 $relationQueryString = "$relationSelect $relationFrom $relationWhere $relationHaving GROUP BY crel.{$contactA}";
1178
1179 $allRelContactDAO = CRM_Core_DAO::executeQuery($relationQueryString);
1180 CRM_Core_DAO::reenableFullGroupByMode();
1181
1182 while ($allRelContactDAO->fetch()) {
1183 $relationQuery->convertToPseudoNames($allRelContactDAO);
1184 $row = [];
1185 // @todo pass processor to fetchRelationshipDetails and set fields directly within it.
1186 self::fetchRelationshipDetails($allRelContactDAO, $relationReturnProperties, $relationshipKey, $row);
1187 foreach (array_keys($relationReturnProperties) as $property) {
1188 if ($property === 'location') {
1189 // @todo - simplify location in self::fetchRelationshipDetails - remove handling here. Or just call
1190 // $processor->setRelationshipValue from fetchRelationshipDetails
1191 foreach ($relationReturnProperties['location'] as $locationName => $locationValues) {
1192 foreach (array_keys($locationValues) as $locationValue) {
1193 $key = str_replace(' ', '_', $locationName) . '-' . $locationValue;
1194 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $key, $row[$relationshipKey . '__' . $key]);
1195 }
1196 }
1197 }
1198 else {
1199 $processor->setRelationshipValue($relationshipKey, $allRelContactDAO->refContact, $property, $row[$relationshipKey . '_' . $property]);
1200 }
1201 }
1202 }
1203 }
1204 }
1205
1206 }