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